我正在 swagger 中编写 openapi 规范来上传图像并获取图像,但我不确定应该使用哪种格式和类型。以下是我尝试过的示例:
/uploadimage:
post:
tags:
- images
summary: to upload image
requestBody:
content:
application/json:
schema:
type: object
properties:
imageID:
type: integer
example: 103983
image:
type: string
formate: byte
有两种方法可以做到这一点。
首先也是最简单的,您可以使用相关媒体类型直接上传文件。例如,
requestBody:
content:
image/png: means: content is an image in a byte array.
schema:
type: string
format: binary
这很简单的原因是客户端很容易拨打这个电话:
POST /my-path HTTP/1.1
Content-Type: image/png
[image file byte array here]
如果您想与请求一起发送其他元数据(正如您的问题示例中所示),您应该使用多部分表单请求。例如,
requestBody:
content:
multipart/form-data: # means: content consists of multiple bits jammed together
schema:
type: object
properties:
imageID: # the metadata you want to send with the image
type: integer
example: 103983
image: # the actual image as a byte array
type: string
format: binary
多部分请求的问题在于您的客户拨打电话很复杂。调用上面的端点如下所示:
POST /my-path HTTP/1.1
Content-Type: multipart/form-data; boundary=xxx
--xxx
Content-Disposition: form-data; name="imageID"
1195
--xxx
Content-Disposition: form-data; name="filename"; filename="my-file.png"
Content-Type: image/png
[image file byte array here]
因此,即使您可以通过文件传递元数据,但仅传递文件要简单得多。