Springdoc、OpenApi如何编写multipart/form-data、文件上传接口
先上swagger官方文档:
https://swagger.io/specification/#schema
目前我使用的springdoc版本为1.69 参考内容:
Special Considerations for multipart Content
It is common to use multipart/form-data as a Content-Type when transferring request bodies to operations. In contrast to 2.0, a schema is REQUIRED to define the input parameters to the operation when using multipart content. This supports complex structures as well as supporting mechanisms for multiple file uploads.
When passing in multipart types, boundaries MAY be used to separate sections of the content being transferred — thus, the following default Content-Type s are defined for multipart :
- If the property is a primitive, or an array of primitive values, the default Content-Type is
text/plain - If the property is complex, or an array of complex values, the default Content-Type is
application/json - If the property is a
type: string with format: binary or format: base64 (aka a file object), the default Content-Type is application/octet-stream
翻译过来就是:
multipart内容的特殊注意事项
在将请求体传输到操作时,通常使用 multipart/form-data 作为 Content-Type。与2.0不同,在使用多部分内容时,模式是 REQUIRED,用于定义操作的输入参数。这支持复杂的结构以及支持多文件上传的机制。
当传递多部分类型时,边界可用于分隔正在传递的内容的各个部分ーー因此,为多部分定义了以下默认内容类型:
- 如果属性是基元或基元值数组,则默认 Content-Type 为 text/plain
- 如果属性是复杂的,或者是复杂值的数组,默认的 Content-Type 是 application/json
- 如果属性是 type: string,格式为: binary 或 format: base64(又名 file 对象) ,则默认的 Content-Type 是 application/octet-stream
范例Examples:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
type: object
properties: {}
profileImage:
type: string
format: binary
children:
type: array
items:
type: string
addresses:
type: array
items:
type: '#/components/schemas/Address'
根据上面的说明写出springboot中springdoc相关接口代码: (可以把CommonResult改为String)
@Operation(summary = "上传文件")
@PostMapping("/files/upload")
@RequestBody(content = {@Content(
mediaType = "multipart/form-data",
schema = @Schema(type = "object"),
schemaProperties = {
@SchemaProperty(
name = "multipartFile",
schema = @Schema(type = "string",format = "binary")
),
@SchemaProperty(
name = "info",
schema = @Schema(type = "object")
)}
)})
public CommonResult<String> upload(MultipartFile multipartFile,
String info){
return CommonResult.success(multipartFile.toString() + info);
}
http://localhost:8888/v3/api-docs中:
{
"/files/upload": {
"post": {
"tags": [
"文件管理"
],
"summary": "上传文件",
"operationId": "upload",
"requestBody": {
"content": {
"application/form-data": {
"schema": {
"type": "object",
"properties": {
"file": {
"type": "string",
"format": "binary"
},
"info": {
"type": "object"
}
}
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"$ref": "#/components/schemas/CommonResultString"
}
}
}
}
}
}
}
}
swagger-ui中:
发送的请求和响应:
成功!
总结:官方文档得仔细看
|