将 multipart/form-data 用作将请求正文传输到操作时的 Content-Type 非常常见。与 2.0 相比,需要使用 schema 来定义使用 multipart 内容时操作的输入参数。这支持复杂结构以及对多个文件上传的支持机制。
在 multipart/form-data 请求正文中,每个 schema 属性或 schema 数组属性的每个元素都在有效负载中占据一部分,并具有 [RFC7578] 定义的内部标头。可以在关联的 编码对象 中指定 multipart/form-data 请求正文的每个属性的序列化策略。
在传递 multipart 类型时,可以使用边界来分隔正在传输的内容的部分 - 因此,为 multipart 定义了以下默认 Content-Type
- 如果属性是原始类型或原始值的数组,则默认的 Content-Type 为
text/plain - 如果属性是复杂类型或复杂值的数组,则默认的 Content-Type 为
application/json - 如果属性是带
contentEncoding的type: string,则默认的 Content-Type 为application/octet-stream
根据 JSON Schema 规范,如果不存在 contentEncoding,则 contentMediaType 将被视为存在 contentEncoding: identity。虽然这对于将 text/html 等文本文档嵌入到 JSON 字符串中很有用,但对于 multipart/form-data 部分则没有用,因为它只会导致文档被视为 text/plain 而不是其实际媒体类型。如果不需要 contentEncoding,请使用不带 contentMediaType 的编码对象。
示例
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
# default Content-Type for objects is `application/json`
type: object
properties: {}
profileImage:
# Content-Type for application-level encoded resource is `text/plain`
type: string
contentMediaType: image/png
contentEncoding: base64
children:
# default Content-Type for arrays is based on the _inner_ type (`text/plain` here)
type: array
items:
type: string
addresses:
# default Content-Type for arrays is based on the _inner_ type (object shown, so `application/json` in this example)
type: array
items:
type: object
$ref: '#/components/schemas/Address'
引入了 encoding 属性,使您可以控制 multipart 请求正文部分的序列化。此属性仅适用于 multipart 和 application/x-www-form-urlencoded 请求正文。