Filter filter to get MultipartFile file

After using the arg0 parameter in the filter doFilter to obtain the HttpServletRequest, obtain the MultipartFile file. After searching, many people say that this method can be used

The common method on the Internet, Xiaobian tested that the size of parts is 0, and the file cannot be accessed.

@Override
protected void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws ServletException, IOException {
    
    
HttpServletRequest request = (HttpServletRequest) arg0;
    Collection<Part> parts = request.getParts();
    for (Part part : parts) {
    
    
        if (part.getContentType() != null && part.getSize() > 0) {
    
    
            String fileName = part.getSubmittedFileName();
            InputStream inputStream = part.getInputStream();
            // do something with the file
        }
    }
}

So through the debug operation, it was found that MultipartFile does exist in HttpServletRequest, but in its subclass DefaultMultipartHttpServletRequest, it finally tried to use this method to obtain the file content

Feasible method

@Override
protected void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws ServletException, IOException {
    
    
    DefaultMultipartHttpServletRequest defaultMultipartHttpServletRequest = (DefaultMultipartHttpServletRequest) arg0;
                Set<Map.Entry<String, MultipartFile>> entries = defaultMultipartHttpServletRequest.getFileMap().entrySet()
               
                for (Map.Entry<String, MultipartFile> entry : entries) {
    
    
                //文件参数名称
                    String fileParmsName = entry.getKey();
                    //文件
                    MultipartFile value = entry.getValue();
                    //文件名称
                    String fileName = value.getName();
                    }
                }
}

Guess you like

Origin blog.csdn.net/qq_46645840/article/details/130847470