springfox-swagger3上传文件
源代码
/**
* 头像上传
*/
@PostMapping(value = "/avatar")
@ApiOperation(value = "头像上传",httpMethod = "POST")
public String avatarUpload( @ApiParam(name = "file",value = "要上传的头像")
@RequestParam("file")
MultipartFile file){
try {
return ossClient.uploadAvatar(file);
} catch (Exception e) {
return "上传失败";
}
}
Swagger文档
后端报错:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
解决
将方法参数中的@RequestParam("file")
改为: @RequestPart("file")
@RequestPart()
注解的文档说明:
可用于将“multipart/form-data”请求的一部分与方法参数相关联的注释。
支持的方法参数类型包括结合 Spring 的MultipartFile抽象的MultipartResolver ,结合 Servlet 3.0 多部分请求的javax.servlet.http.Part ,或者对于任何其他方法参数,部分的内容通过HttpMessageConverter考虑到请求部分的“Content-Type”标头。这类似于RequestBody根据非多部分常规请求的内容解析参数。
请注意,@ RequestParam注解也可用于将“multipart/form-data”请求的部分与支持相同方法参数类型的方法参数相关联。主要区别在于,当方法参数不是 String 或原始MultipartFile / Part时, HttpMessageConverters RequestParam 依赖于通过注册的Converter或PropertyEditor进行类型转换,而RequestPart依赖于@RequestParam考虑到请求部分的“Content-Type”标头. RequestParam可能与名称-值表单字段一起使用,而RequestPart可能与包含更复杂内容的部分(例如 JSON、XML)一起使用。