檔案上傳
在 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 規範的以下章節