swagger2报错"Content type 'multipart/form-data;boundary=----WebKitFormBoundarymuIlI8e7mWlssxDA;charset=UTF-8' not supported"
时间: 2023-07-04 19:18:56 浏览: 203
在Swagger2中,如果API接口中包含文件上传,需要使用@ApiImplicitParam
注解来定义参数。以下是一个示例代码:
@PostMapping("/addAdvert")
@ApiOperation(value = "新增广告")
@ApiImplicitParams({
@ApiImplicitParam(name = "advertDto", value = "广告对象", dataType = "AdvertDTO", paramType = "body"),
@ApiImplicitParam(name = "file", value = "文件", dataType = "__file", paramType = "form")
})
public JsonData<String> addAdvert(@RequestBody AdvertDTO advertDto, MultipartFile file) {
// 处理请求逻辑
}
需要注意的是,@ApiImplicitParam
注解中,paramType
参数需要设置为form
,表示这是一个表单类型的参数。另外,由于Swagger2默认不支持文件上传,因此需要使用__file
类型来表示文件类型。同时,需要在Swagger2配置中添加对MultipartFile
类型的支持,可以在Swagger2的配置类中添加如下配置:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.globalOperationParameters(
Collections.singletonList(new ParameterBuilder()
.name("Authorization")
.description("认证Token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build()))
.directModelSubstitute(MultipartFile.class, byte[].class);
}
在上述配置中,directModelSubstitute
方法用于将MultipartFile
类型替换成byte[]
类型,以使Swagger2能够正确地解析文件类型。需要注意的是,这种方式会将所有的MultipartFile
类型都替换成byte[]
类型,因此如果API接口中有其他参数类型也为MultipartFile
,则需要自行处理。
相关推荐












