开发过程中遇到过滤文件类型的问题,需要校验文件的头信息,,在过滤器中通过request获取文件流信息 但是后续的controller中的MultipartFile一直都是空的,网上的网友的方案使用了一堆比如 使用BodyReaderHttpServletRequestWrapper 封装 但是不好用,说一下我自己的解决方案。
直接上代码:一目了然
@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;String contentType = request.getContentType();if(null != contentType && contentType.contains("multipart/form-data")){//说明是文件上传 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();MultipartHttpServletRequest resolveMultipart = commonsMultipartResolver.resolveMultipart(req); boolean b = true;Map<String, MultipartFile> fileMap = resolveMultipart.getFileMap();for (String key : fileMap.keySet()) {MultipartFile multipartFile = fileMap.get(key);InputStream is = multipartFile.getInputStream();//你的过滤逻辑b=false;}}} if(b){chain.doFilter(resolveMultipart, response);}}else{chain.doFilter(request, response);}}
这样过滤以后,后续的controller中的MultipartFile就不为空了。搞定!!!