I am refactoring some legacy code used to upload files using Commons Fileupload and JSPs, to use Spring Controllers. Given that lots of the code for file uploads is based on Commons Fileupload, I want to reuse that code. The first attempt was made directly moving the code from the JSP to a Spring Controller, like this:
@RequestMapping(path = { "/my/file/upload/request/mapping" })
public ModelAndView myControllerMethod(HttpServletRequest request, HttpServletResponse response){
List<FileItem> items = null;
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
items = upload.parseRequest(request);
System.out.println("number of items: " + (items != null ? items.size() : "null"));
}
...
Although the program enters the if
, recognizing it as a multipart request, this always shows number of items: 0
.
I have included a MultipartViewResolver
like this:
@Configuration
@EnableWebMvc
@SuppressWarnings("deprecation")
public class WebMvcConfiguration extends WebMvcConfigurerAdapter{
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(maxFileUploadSizeBytes);
return multipartResolver;
}
but the result is the same with or without it.
As stated in many places (like here (Baeldung) and here (SO)), it seems that Commons Fileupload cannot read the multipart because it has already been read by Spring. So the solution seems to be to disable Spring multipart support. Many posts tell how to do that for Spring Boot but I have no idea about how to do that for raw Spring 5. Any idea about how to do it?
Note: I've also tried to get the multipart files using the Spring way, like this:
@RequestMapping(path = { "/my/file/upload/request/mapping" })
public ModelAndView myControllerMethod(@RequestParam MultipartFile file){
and even @RequestParam MultipartFile[] files
but I obtain null files or empty files array respectively. Again, I've checked with Firefox console that the request being made is exactly the same as with the old JSP code, which worked, so the problem is not in the request being made.