如何通过OpenAPI/Swagger CodeGen限制上传文件的MIME类型?
限制文件上传MIME类型的OpenAPI配置方案
问题背景
我使用OpenAPI 3.0.1和swagger-codegen-maven-plugin 3.0.27(版本可调整),已通过以下OpenAPI定义实现文件及其他数据的上传:
/myobject/: post: tags: - my-objects operationId: add requestBody: content: multipart/form-data: schema: $ref: '#/components/schemas/MyDTO' required: true ... schemas: MyDTO: type: object properties: ... dataFile: type: string format: binary
现在需要将dataFile的上传MIME类型限制为application/vnd.ms-excel和text/csv,该如何通过OpenAPI规范和Swagger CodeGen实现?
解决方案
1. 修改OpenAPI规范定义
有两种方式可以在OpenAPI中声明文件的允许MIME类型:
方式一:在Schema字段中指定contentMediaType
直接在MyDTO的dataFile属性里添加contentMediaType,多个MIME类型用数组形式声明:
schemas: MyDTO: type: object properties: ... dataFile: type: string format: binary contentMediaType: - application/vnd.ms-excel - text/csv
方式二:在请求体的multipart配置中指定mediaTypes
也可以在requestBody的multipart/form-data下,针对dataFile字段单独配置允许的MIME类型:
/myobject/: post: tags: - my-objects operationId: add requestBody: content: multipart/form-data: schema: $ref: '#/components/schemas/MyDTO' encoding: dataFile: contentType: "application/vnd.ms-excel, text/csv" required: true
2. Swagger CodeGen适配注意事项
- 当前使用的
swagger-codegen-maven-plugin 3.0.27已经支持解析上述两种配置,生成的客户端代码会自动限制文件选择的MIME类型;服务端代码(如Spring Boot)会在接口层面带上对应的MIME类型约束。 - 如果遇到配置解析异常,可以将插件版本升级到
3.0.36或更高,这些版本对OpenAPI 3.0的文件类型约束支持更完善。 - 服务端若需要强校验,生成代码后可结合框架校验机制(比如Spring的
@Valid配合自定义校验注解),确保实际上传文件类型符合要求。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

