最近在系统的学习springmvc,在写demo的时候发现multipartHttpServletRequest.getFileMap();
一直是空,找解决方案都不是很理想,后来去阅读了一下官网说明原来在定义文件解析器MultipartResolver的时候,没有设置resolveLazily属性为true(默认值为false)
最终实现多文件上传代码如下:
//文件解析器
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
multipartResolver.setDefaultEncoding("UTF-8");
//问题所在
multipartResolver.setResolveLazily(true);
return multipartResolver;
}
controller里就可以获取到文件流了
//支持批量上传
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String upload(HttpServletRequest request) {
MultipartHttpServletRequest multipartHttpServletRequest = this.resolver.resolveMultipart(request);
Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
System.out.println(fileMap.isEmpty());
fileMap.forEach((key, file) -> {
try {
System.out.println(key);
FileUtils.writeByteArrayToFile(new File("/home/sxq/learnspring" + File.separator + file.getOriginalFilename()), file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
return "success";
}
猜测:MultipartResolver在initBinder的时候默认会自动解析request,并清空文件流里的内容,导致在controller中的request获取不到文件流信息,当设置multipartResolver.setResolveLazily(true);
则不会自动解析
如有不对请多指教。