跳至內容

檔案上傳

在 OpenAPI 3.0 中,您可以描述直接使用請求內容上傳的檔案,以及使用 multipart 請求上傳的檔案。使用 requestBody 關鍵字來描述包含檔案的請求酬載。在 content 下,指定請求媒體類型(例如 image/pngapplication/octet-stream)。檔案使用 type: string 綱要,其中 format: binaryformat: base64,取決於檔案內容的編碼方式。例如

1
requestBody:
2
content:
3
image/png:
4
schema:
5
type: string
6
format: binary

此定義對應於如下所示的 HTTP 請求

1
POST /upload
2
Host: example.com
3
Content-Length: 808
4
Content-Type: image/png
5
6
[file content goes there]

透過 Multipart 請求上傳

若要描述與其他資料一起傳送的檔案,請使用 multipart 媒體類型。例如

1
requestBody:
2
content:
3
multipart/form-data:
4
schema:
5
type: object
6
properties:
7
orderId:
8
type: integer
9
userId:
10
type: integer
11
fileName:
12
type: string
13
format: binary

對應的 HTTP 請求酬載將包含多個部分

1
POST /upload
2
Host: example.com
3
Content-Length: 2740
4
Content-Type: multipart/form-data; boundary=abcde12345
5
6
--abcde12345
7
Content-Disposition: form-data; name="orderId"
8
9
1195
10
--abcde12345
11
Content-Disposition: form-data; name="userId"
12
13
545
14
--abcde12345
15
Content-Disposition: form-data; name="fileName"; filename="attachment.txt"
16
Content-Type: text/plain
17
18
[file content goes there]
19
--abcde12345--

多檔案上傳

使用 multipart 媒體類型來定義上傳任意數量的檔案(檔案陣列)

1
requestBody:
2
content:
3
multipart/form-data:
4
schema:
5
type: object
6
properties:
7
filename:
8
type: array
9
items:
10
type: string
11
format: binary

對應的 HTTP 請求如下所示

1
POST /upload
2
Host: example.com
3
Content-Length: 2740
4
Content-Type: multipart/form-data; boundary=abcde12345
5
6
--abcde12345
7
Content-Disposition: form-data; name="fileName"; filename="file1.txt"
8
Content-Type: text/plain
9
10
[file content goes there]
11
--abcde12345
12
Content-Disposition: form-data; name="fileName"; filename="file2.png"
13
Content-Type: image/png
14
15
[file content goes there]
16
------WebKitFormBoundaryWfPNVh4wuWBlyEyQ
17
Content-Disposition: form-data; name="fileName"; filename="file3.jpg"
18
Content-Type: image/jpeg
19
20
[file content goes there]
21
--abcde12345--

參考資料

如需有關 OpenAPI 中檔案上傳的更多資訊,請參閱 OpenAPI 3.0 規範的以下章節

檔案上傳的考量事項

multipart 內容的特殊考量事項

找不到您要的內容嗎?向社群提問
發現錯誤?讓我們知道