文件上传
Swagger 2.0 支持使用 Content-Type: multipart/form-data
发送的文件上传。也就是说,您的 API 服务器必须为此操作使用 multipart/form-data
1consumes:2 - multipart/form-data
操作有效负载使用 formData
参数(而不是主体参数)定义。文件参数必须具有 type: file
1paths:2 /upload:3 post:4 summary: Uploads a file.5 consumes:6 - multipart/form-data7 parameters:8 - in: formData9 name: upfile10 type: file11 description: The file to upload.
此定义对应于以下 HTTP 请求
1POST /upload2Host: example.com3Content-Type: multipart/form-data; boundary=abcde123454Content-Length: 2045
6--abcde123457Content-Disposition: form-data; name="upfile"; filename="example.txt"8Content-Type: text/plain9
10File contents go here.11--abcde12345--
Swagger UI 使用文件输入控件显示文件参数,允许用户浏览要上传的本地文件。
上传文件 + 其他数据
文件参数可以与其他表单数据一起发送
1parameters:2 - in: formData3 name: upfile4 type: file5 required: true6 description: The file to upload.7 - in: formData8 name: note9 type: string10 required: false11 description: Description of file contents.
相应的 HTTP 请求有效负载将包括多个部分
1POST /upload2Host: example.com3Content-Type: multipart/form-data; boundary=abcde123454Content-Length: 3325
6--abcde123457Content-Disposition: form-data; name="upfile"; filename="example.txt"8Content-Type: text/plain9
10File contents go here.11--abcde1234512Content-Disposition: form-data; name="note"13
14Uploading a file named "example.txt"15--abcde12345--
多文件上传
您可以有多个命名的文件参数,每个参数单独定义
1parameters:2 - in: formData3 name: upfile14 type: file5 required: true6 - in: formData7 name: upfile28 type: file9 required: false10 - in: formData11 name: upfile312 type: file13 required: false
但是,不支持上传任意数量的文件(文件数组)。在 https://github.com/OAI/OpenAPI-Specification/issues/254 有一个开放的功能请求。目前,您可以使用二进制字符串数组作为上传任意数量文件的解决方法
1type: array2items:3 type: string4 format: binary
请注意,这不会在 Swagger UI 中生成文件上传界面。
常见问题解答
我可以通过 PUT 上传文件吗?
Swagger 2.0 支持使用 Content-Type: multipart/form-data
的文件上传请求,但不关心 HTTP 方法。您可以使用 POST、PUT 或任何其他方法,前提是该操作使用 multipart/form-data
。Swagger 2.0 不支持有效负载仅为原始文件内容的情况,因为它们不是 multipart/form-data
。也就是说,Swagger 2.0 不支持类似以下的内容
1curl --upload-file archive.zip http://example.com/upload
另请注意,Swagger UI 中的文件上传仅适用于 POST 请求,因为浏览器中的 HTML 表单仅支持 GET 和 POST 方法。
我可以为上传的文件定义 Content-Type 吗?
这在 OpenAPI 3.0 中受支持,但在 OpenAPI/Swagger 2.0 中不受支持。在 2.0 中,您可以说某个操作接受文件,但您不能说此文件是特定类型或结构的。
作为一种解决方法,供应商扩展可用于扩展此功能,例如
1- in: formData2 name: zipfile3 type: file4 description: Contents of the ZIP file.5 x-mimetype: application/zip