檔案上傳
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