跳至內容

檔案上傳

Swagger 2.0 支援使用 Content-Type: multipart/form-data 傳送的檔案上傳。也就是說,您的 API 伺服器必須使用 multipart/form-data 才能進行此操作

1
consumes:
2
- multipart/form-data

操作酬載是使用 formData 參數(而非主體參數)定義的。檔案參數必須具有 type: file

1
paths:
2
/upload:
3
post:
4
summary: Uploads a file.
5
consumes:
6
- multipart/form-data
7
parameters:
8
- in: formData
9
name: upfile
10
type: file
11
description: The file to upload.

此定義對應於下列 HTTP 請求

1
POST /upload
2
Host: example.com
3
Content-Type: multipart/form-data; boundary=abcde12345
4
Content-Length: 204
5
6
--abcde12345
7
Content-Disposition: form-data; name="upfile"; filename="example.txt"
8
Content-Type: text/plain
9
10
File contents go here.
11
--abcde12345--

Swagger UI 會使用檔案輸入控制項顯示檔案參數,讓使用者可以瀏覽要上傳的本機檔案。

上傳檔案 + 其他資料

檔案參數可以與其他表單資料一起傳送

1
parameters:
2
- in: formData
3
name: upfile
4
type: file
5
required: true
6
description: The file to upload.
7
- in: formData
8
name: note
9
type: string
10
required: false
11
description: Description of file contents.

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

1
POST /upload
2
Host: example.com
3
Content-Type: multipart/form-data; boundary=abcde12345
4
Content-Length: 332
5
6
--abcde12345
7
Content-Disposition: form-data; name="upfile"; filename="example.txt"
8
Content-Type: text/plain
9
10
File contents go here.
11
--abcde12345
12
Content-Disposition: form-data; name="note"
13
14
Uploading a file named "example.txt"
15
--abcde12345--

多次上傳

您可以有多個具名的檔案參數,每個參數都是個別定義的

1
parameters:
2
- in: formData
3
name: upfile1
4
type: file
5
required: true
6
- in: formData
7
name: upfile2
8
type: file
9
required: false
10
- in: formData
11
name: upfile3
12
type: file
13
required: false

但是,不支援上傳任意數量的檔案(檔案陣列)。在 https://github.com/OAI/OpenAPI-Specification/issues/254 有一個開啟的功能要求。目前,您可以使用二進位字串陣列作為上傳任意數量的檔案的解決方法

1
type: array
2
items:
3
type: string
4
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 不支援類似下列的項目

1
curl --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: formData
2
name: zipfile
3
type: file
4
description: Contents of the ZIP file.
5
x-mimetype: application/zip

找不到您要尋找的內容嗎?詢問社群
發現錯誤?請告訴我們