Search code examples
springspring-mvcspring-bootjquery-file-upload

How to upload multiple files at once using MultipartConfigElement in Spring Boot?


I am using Spring Boot 1.1.3 with the CommonsMultipartResolver to allow uploading of multiple files at once.

I get this stacktrace when I try to upload a file bigger than 1 MB:

Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: 
The field files[] exceeds its maximum permitted size of 1048576 bytes.
    at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl$1.raiseError(FileUploadBase.java:637)
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76)
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)

I tried setting the max upload size like this:

public MultipartResolver multipartResolver()
{
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setMaxUploadSize( 100 * MEGABYTE_IN_BYTES );
    return resolver;
}

However, this does not work. I have found this Spring guide on upoading files and there they use MultipartConfigFactory instead. However, I now need to use the MultipartFile class instead of MultipartHttpServletRequest in my controller.

With the MultipartHttpServletRequest I could do getFileMap() to get all the files, but there is no such method on MultipartFile.

Any ideas on how to work with MultipartConfigFactory and multiple files? I am using jquery-file-upload on the client if that would matter.


Solution

  • Seems there is no need to use the MultipartFile in the Controller, you can also use the MultipartHttpServletRequest. This is the signature of my @RestController annotated class:

    @RequestMapping(value = "/{datasheetId}/addDoc", method = RequestMethod.POST)
    @Secured(ROLE_USER)
    public ResponseEntity<?> addDocumentToDatasheet( Principal principal,
                                                     @PathVariable("datasheetId") long datasheetId,
                                                     MultipartHttpServletRequest request ) throws IOException
    {
         Map<String, MultipartFile> fileMap = request.getFileMap();
         // handle fileMap further...
    }