多部分请求
多部分请求将一个或多个数据集组合到一个主体中,并用边界分隔。您通常将这些请求用于文件上传,以及在单个请求中传输多种类型的数据(例如,文件以及 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
默认情况下,根据描述请求部分的 schema
属性类型,自动设置各个请求部分的 Content-Type
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--