无法从multipartHttpServletRequest.getFile(“files”)获取文件,但从request.getPart(“files”)获取A部件

时间:2016-12-19 01:21:31

标签: spring-mvc spring-boot spring-security

这是我的全部功能

@RequestMapping(value = "/file",headers = "content-type=multipart/*", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(HttpServletRequest request,Model model) throws IOException {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
    MultipartFile files = multipartHttpServletRequest.getFile("files");
    if(files!=null) {
        //do somethings
        log.info(files);
        return "true";
    }else {
        Part file = request.getPart("files");
        log.info(file.getSize());
        return "false";
    }
}

并且MultipartFile files为空,但Part file是我预期的结果; 为什么?以及如何直接从multipartHttpServletRequest.getFile("files")

获取文件

我的CommonsMultipartResolver配置就像这样

@Bean
public CommonsMultipartResolver multipartResolver(){
    CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
    commonsMultipartResolver.setMaxInMemorySize(3000000);
    return  commonsMultipartResolver;
}

1 个答案:

答案 0 :(得分:1)

确保您在web.xml中有多部分过滤器。如果您正在使用它,那么应该将放在 Spring Security过滤器链之前。

<filter>
  <filter-name>multipartFilter</filter-name>
  <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>multipartFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

将多部分解析器定义为(名称很重要):

@Bean
public MultipartResolver filterMultipartResolver()
{
    return new StandardServletMultipartResolver();
}

由于request.getPart有效,你有最新版本的Servlet API,你不需要Commons FileUpload bean / dependency,remove。