How to handle MaxUploadSizeExceededException

This is an old question so I’m adding it for the future people (including future me) who are struggling to get this working with Spring Boot 2.

At first you need to configure the spring application (in properties file):

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

If you’re using embedded Tomcat (and most likely you are, as it comes as standard) it’s also important to configure Tomcat not to cancel the request with large body

server.tomcat.max-swallow-size=-1

or at least set it to relatively big size

server.tomcat.max-swallow-size=100MB

If you will not set maxSwallowSize for Tomcat, you might waste lots of hours debugging why the error is handled but browser gets no response – that’s because without this configuration Tomcat will cancel the request, and even though you’ll see in the logs that application is handling the error, the browser already received cancellation of request from Tomcat and isn’t listening for the response anymore.

And to handle the MaxUploadSizeExceededException you can add ControllerAdvice with ExceptionHandler.

Here’s a quick example in Kotlin that simply sets a flash attribute with an error and redirects to some page:

@ControllerAdvice
class FileSizeExceptionAdvice {
    @ExceptionHandler(MaxUploadSizeExceededException::class)
    fun handleFileSizeException(
        e: MaxUploadSizeExceededException, 
        redirectAttributes: RedirectAttributes
    ): String {
        redirectAttributes.addFlashAttribute("error", "File is too big")
        return "redirect:/"
    }
}

NOTE: if you want to handle MaxUploadSizeExceededException with ExceptionHandler directly in your controller class, you should configure following property:

spring.servlet.multipart.resolve-lazily=true

otherwise that exception will be triggered before the request is mapped to controller.

Leave a Comment