问题描述
SpringBoot项目中用MultipartFile获取到的file为null(不加@RequestParam(“file”)注解),如果加上@RequestParam(“file”)注解就报Requied request part ‘file’ is not present 错误。
用Postman和Swagger调都是一样的问题,并且F12检查前端请求参数也是没问题的,真是奇怪了。
接口代码如下:
1 2 3 4 @RequestMapping(value = "/upload", method = RequestMethod.POST) public ResponseMsg<Attachment> upload (@RequestParam("file") final MultipartFile file, final HttpServletRequest request) { ...... }
Postman部分报错信息如下:
解决方法
网上查到了很多解决方法:
在启动类加@SpringBootApplication(exclude = {MultipartAutoConfiguration.class})注解排除SpringBoot依赖,然后写一个配置文件UploadConfig
1 2 3 4 5 6 7 @Configuration public class UploadConfig { @Bean(name="multipartResolver") public MultipartResolver multipartResolver () { return new CommonsMultipartResolver (); } }
然而问题并没有解决
说前端传的file名不一致,我这边是一致的😂 。
说没加@RequestParam(“file”)注解,经过验证这个注解可有可无。
最后发现是项目中加了过滤器导致的,过滤器是为了request重复使用,但是文件请求类型multipart/form-data和其他类型不一样,所以过滤器没法处理导致进不了Controller。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 @Component @WebFilter @Slf4j public class RequestWrapperFilter implements Filter { @Override public void init (FilterConfig filterConfig) throws ServletException { } @Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletRequest requestWrapper = null ; if (request instanceof HttpServletRequest) { requestWrapper = new BodyReaderHttpServletRequestWrapper ((HttpServletRequest) request); } if (null == requestWrapper) { log.error("包装request失败!将返回原来的request" ); chain.doFilter(request, response); } else { log.info("包装request成功" ); chain.doFilter(requestWrapper, response); } } @Override public void destroy () { } }
把@Component和@WebFilter注释掉,临时解决 。