文件上传
在 OpenAPI 3.0 中,您可以描述直接通过请求内容上传的文件和通过 multipart
请求上传的文件。使用 requestBody
关键字来描述包含文件的请求负载。在 content
下,指定请求媒体类型(例如 image/png
或 application/octet-stream
)。文件使用 type: string
模式,带有 format: binary
或 format: base64
,具体取决于文件内容的编码方式。例如
1requestBody:2 content:3 image/png:4 schema:5 type: string6 format: binary
此定义对应于如下所示的 HTTP 请求
1POST /upload2Host: example.com3Content-Length: 8084Content-Type: image/png5
6[file content goes there]
通过 Multipart 请求上传
要描述与其他数据一起发送的文件,请使用 multipart
媒体类型。例如
1requestBody:2 content:3 multipart/form-data:4 schema:5 type: object6 properties:7 orderId:8 type: integer9 userId:10 type: integer11 fileName:12 type: string13 format: binary
相应的 HTTP 请求负载将包括多个部分
1POST /upload2Host: example.com3Content-Length: 27404Content-Type: multipart/form-data; boundary=abcde123455
6--abcde123457Content-Disposition: form-data; name="orderId"8
9119510--abcde1234511Content-Disposition: form-data; name="userId"12
1354514--abcde1234515Content-Disposition: form-data; name="fileName"; filename="attachment.txt"16Content-Type: text/plain17
18[file content goes there]19--abcde12345--
多文件上传
使用 multipart
媒体类型定义上传任意数量的文件(文件数组)
1requestBody:2 content:3 multipart/form-data:4 schema:5 type: object6 properties:7 filename:8 type: array9 items:10 type: string11 format: binary
相应的 HTTP 请求将如下所示
1POST /upload2Host: example.com3Content-Length: 27404Content-Type: multipart/form-data; boundary=abcde123455
6--abcde123457Content-Disposition: form-data; name="fileName"; filename="file1.txt"8Content-Type: text/plain9
10[file content goes there]11--abcde1234512Content-Disposition: form-data; name="fileName"; filename="file2.png"13Content-Type: image/png14
15[file content goes there]16------WebKitFormBoundaryWfPNVh4wuWBlyEyQ17Content-Disposition: form-data; name="fileName"; filename="file3.jpg"18Content-Type: image/jpeg19
20[file content goes there]21--abcde12345--
参考
有关 OpenAPI 中文件上传的更多信息,请参阅 OpenAPI 3.0 规范的以下部分