多部分請求
多部分請求將一組或多組資料組合到單一主體中,並以邊界分隔。您通常會使用這些請求來上傳檔案,以及在單一請求中傳輸多種資料類型(例如,檔案以及 JSON 物件)。在 OpenAPI 3 中,您以下列方式描述多部分請求
1requestBody:2 content:3 multipart/form-data: # Media type4 schema: # Request payload5 type: object6 properties: # Request parts7 id: # Part 1 (string value)8 type: string9 format: uuid10 address: # Part2 (object)11 type: object12 properties:13 street:14 type: string15 city:16 type: string17 profileImage: # Part 3 (an image)18 type: string19 format: binary
您從 requestBody/content
關鍵字開始。然後,您指定請求資料的媒體類型。檔案上傳通常使用 _multipart/form-data_
媒體類型,而混合資料請求通常使用 _multipart/mixed_
。在媒體類型下方,放入 schema
關鍵字,以表示您開始描述請求酬載。您將請求的個別部分描述為 schema
物件的屬性。如您所見,多部分請求可以包含各種資料:字串、JSON 格式的物件和二進位資料。您也可以指定一或多個要上傳的檔案。(若要了解更多資訊,請參閱檔案上傳。)上述範例對應於下列請求
1POST /upload HTTP/1.12Content-Length: 4283Content-Type: multipart/form-data; boundary=abcde123454
5--abcde123456Content-Disposition: form-data; name="id"7Content-Type: text/plain8
9123e4567-e89b-12d3-a456-42665544000010--abcde1234511Content-Disposition: form-data; name="address"12Content-Type: application/json13
14{15 "street": "3, Garden St",16 "city": "Hillsbery, UT"17}18--abcde1234519Content-Disposition: form-data; name="profileImage "; filename="image1.png"20Content-Type: application/octet-stream21
22{…file content…}23--abcde12345--
指定 Content-Type
根據預設,個別請求部分的 Content-Type
會根據描述請求部分的 schema
屬性類型自動設定
Schema 屬性類型
Content-Type
基本類型或基本類型陣列
text/plain
複雜值或複雜值陣列
application/json
binary
或 base64
格式的字串
application/octet-stream
若要為請求部分設定特定的 Content-Type
,請使用 encoding/_{property-name}_/contentType
欄位。您將 encoding
新增為媒體類型屬性的子屬性,與 schema
所在層級相同。在以下範例中,我們將多部分請求的 profileImage
部分的 contentType
設定為 image/png, image/jpg
1requestBody:2 content:3 multipart/form-data:4 schema:5 type: object6 properties: # Request parts7 id:8 type: string9 format: uuid10 address:11 type: object12 properties:13 street:14 type: string15 city:16 type: string17 profileImage:18 type: string19 format: base6420 encoding: # The same level as schema21 profileImage: # Property name (see above)22 contentType: image/png, image/jpeg
指定自訂標頭
多部分請求的部分通常不使用任何標頭,除了 Content
。如果您需要包含自訂標頭,請使用 encoding/_{property-name}_/headers
欄位來描述這些標頭(請參閱下方)。如需描述標頭的完整資訊,請參閱描述參數。以下是為多部分請求的部分定義自訂標頭的範例
1requestBody:2 content:3 multipart/form-data:4 schema:5 type: object6 properties:7 id:8 type: string9 format: uuid10 profileImage:11 type: string12 format: binary13 encoding:14 profileImage: # Property name15 contentType: image/png, image/jpeg16 headers: # Custom headers17 X-Custom-Header:18 description: This is a custom header19 schema:20 type: string
此宣告符合下列請求
1POST /upload HTTP/1.12Content-Length: 4283Content-Type: multipart/form-data; boundary=abcde123454
5--abcde123456Content-Disposition: form-data; name="id"7Content-Type: text/plain8
9123e4567-e89b-12d3-a456-42665544000010--abcde1234511Content-Disposition: form-data; name="profileImage"; filename="image1.png"12Content-Type: image/png13X-Custom-Header: x-header14
15{…file content…}16--abcde12345--