OpenAPI 3.1.0多部分表单:如何同时验证文件上传与文件名?
如何在OpenAPI 3.1.0中实现文件上传并验证文件名
你当前的OpenAPI Schema错误地将文件名的验证规则应用在了文件内容上,要同时实现文件上传和文件名格式验证,需要利用OpenAPI 3.1.0中multipart/form-data的encoding配置来单独针对文件名做校验。
原错误代码
"/my-endpoint": { "post": { "requestBody": { "required": true, "content": { "multipart/form-data": { "schema": { "type": "object", "properties": { "file": { "description": "binary file including file extension", "type": "string", "pattern": "filename\\.ext", "format": "binary" } } } } } } } }
修改后的正确Schema
"/my-endpoint": { "post": { "requestBody": { "required": true, "content": { "multipart/form-data": { "schema": { "type": "object", "properties": { "file": { "description": "binary file including file extension", "type": "string", "format": "binary" } } }, "encoding": { "file": { "headers": { "Content-Disposition": { "schema": { "type": "string", "pattern": "^form-data; name=\"file\"; filename=\".*\\.ext\"$" } } } } } } } } } }
核心修改说明
- 保留
file字段的type: string和format: binary,这部分负责定义文件内容的类型,确保接口能正确接收二进制文件。 - 添加
encoding配置节点:在multipart/form-data下新增encoding,针对file字段设置头部校验规则。 - 校验
Content-Disposition头部:通过匹配该头部的完整格式,其中filename=".*\\.ext"部分用于验证文件名必须以.ext结尾,你可以根据需求调整正则,比如改成filename=".*\\.(jpg|png)"来支持多种后缀。
内容的提问来源于stack exchange,提问作者myol
相关产品推荐
相关产品推荐

