跳到内容

文件上传

在 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 内容的特殊注意事项

没有找到您要找的内容? 向社区提问
发现错误? 请告知我们