从Swagger2 升级到 Swagger3 之后发现对于附件出现了问题。
<dependency>
<groupId>org.springdocgroupId>
<artifactId>springdoc-openapi-uiartifactId>
<version>1.7.0version>
dependency>
在Swagger2时的样子:可以看到Request body是可以选择application/octet-stream
的
升级到Swagger3之后:可以看到Request body只有application/json
能选择,也就是说请求体的类型被定死了。
## 解决方案
问题解决之前的代码:
@Operation(summary = "上传附件")
@PostMapping("uploadAttachment")
public H3yunObject uploadAttachment(@Parameter(description = "表单编码") @RequestParam("schemaCode") String schemaCode,
@Parameter(description = "表单ObjectId值") @RequestParam("bizObjectId") String bizObjectId,
@Parameter(description = "控件编码", example = "F0000001") @RequestParam("filePropertyName") String filePropertyName,
@RequestBody MultipartFile file) throws IOException {
log.info("文件上传参数:schemaCode = {}, bizObjectId = {}, filePropertyName = {}", schemaCode, bizObjectId, filePropertyName);
if (file != null) {
log.info("文件名:{}", file.getOriginalFilename());
}
return null;
}
修改代码为:
@Operation(summary = "上传附件")
@PostMapping("uploadAttachment")
public H3yunObject uploadAttachment(@Parameter(description = "表单编码") @RequestParam("schemaCode") String schemaCode,
@Parameter(description = "表单ObjectId值") @RequestParam("bizObjectId") String bizObjectId,
@Parameter(description = "控件编码", example = "F0000001") @RequestParam("filePropertyName") String filePropertyName,
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "附件",
content = @Content(
mediaType = "multipart/form-data",
schema = @Schema(type = "object"),
schemaProperties = {
@SchemaProperty(
name = "file",
schema = @Schema(type = "string", format = "binary")
)
}
)
) MultipartFile file) throws IOException {
log.info("文件上传参数:schemaCode = {}, bizObjectId = {}, filePropertyName = {}", schemaCode, bizObjectId, filePropertyName);
if (file != null) {
log.info("文件名:{}", file.getOriginalFilename());
}
return null;
}
修改代码后重启应用,可以发现请求体成功变成multipart/form-data
选择一个文件点击执行
可以看到后端成功拿到文件了。
很简单的解决方案,把@RequestBody MultipartFile file
这个参数的RequestBody注解换成swagger
的就成了,目的是显示指定请求体具体字段的类型。
换了之后变成
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "附件",
content = @Content(
mediaType = "multipart/form-data",
schema = @Schema(type = "object"),
schemaProperties = {
@SchemaProperty(
name = "file",
schema = @Schema(type = "string", format = "binary")
)
}
)
) MultipartFile file