Question

I figured out that Apache Tomcat allows for the following configuration, In hard-coded or Annotation approach. I'm not sure if the max-file-size is calculated during the upload process or after the file is uploaded to a temp place. The documentation indicates the followings :

The @MultipartConfig annotation supports the following optional attributes:

location: An absolute path to a directory on the file system. The location attribute does not support a path relative to the application context. This location is used to store files temporarily while the parts are processed or when the size of the file exceeds the specified fileSizeThreshold setting. The default location is "".

fileSizeThreshold: The file size in bytes after which the file will be temporarily stored on disk. The default size is 0 bytes.

MaxFileSize: The maximum size allowed for uploaded files, in bytes. If the size of any uploaded file is greater than this size, the web container will throw an exception (IllegalStateException). The default size is unlimited.

maxRequestSize: The maximum size allowed for a multipart/form-data request, in bytes. The web container will throw an exception if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.

annotation approach :

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, 
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

I appreciate it if anyone can clarify if the MaxFileSize is calculated during the upload process and How to handle this exception in servlet.

Was it helpful?

Solution

If the size of the file being uploaded exceeds the configured maximum, an IllegalStateException exception will be thrown.

This happens when you attempt to get the Parts of the request by calling the HttpServletRequest.getParts() or HttpServletRequest.getPart(). So the easiest way is to just simply put this into a try-catch block like this:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    Parts parts = null
    try {
        parts = request.getParts();
    } catch (IllegalStateException e) {
        // File or request is too big!
        // Here you can send back an error message to the client,
        // I just send back an HTTP 400 (Bad Request) error page.
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // Process parts...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top