Search code examples
spring-boottomcatfile-uploadmultipart

Tomcat Servlet 3.0 multipart file upload name clash in temp folder


It appears Tomcat is not handling parallel uploads of the same multipart file by two different users.

Test

  • Two sessions/users A & B
  • Both upload a 20MB file with the same name foo.pdf more or less at the same time
  • Servlet 3.0 Request with default configuration stores the two files in the tmp folder
  • Both threads try to write that foo.pdf into the tmp folder

Result

  • The uploaded document is corrupt (two streams writing to it)
  • The slower request will fail with a FileNotFoundException as the tmp file was already deleted by the cleanup task of the faster request.

Is there a way to avoid this - other than setting fileSizeThreshold higher than maxFileSize so it would never be written to disk in the first place.

Side note: this is a Spring Boot 2.1 application but this is irrelevant as it uses this Servlet 3.0 implementation by default.


Solution

  • I have an answer but it's not really satisfactory. We didn't figure out how to make this work with Tomcat's Servlet 3.0 implementation. However, once we switched to Apache commons-fileupload all was well.

    So, for Spring (Boot) applications you would

    • set spring.servlet.multipart.enabled: false
    • configure a bean of type CommonsMultipartResolver with a name of multipartResolver
    • add the commons-fileupload dependency