Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

MaxUploadSizeExceededException in Spring

$
0
0

1. Overview

In the Spring framework, a MaxUploadSizeExceededException is thrown when an application attempts to upload a file whose size exceeds a certain threshold as specified in the configuration.

In this tutorial, we will take a look at how to specify a maximum upload size. Then we will show a simple file upload controller and discuss different methods for handling this exception.

2. Setting a Maximum Upload Size

By default, there is no limit on the size of files that can be uploaded. In order to set a maximum upload size, you have to declare a bean of type MultipartResolver.

Let’s see an example that limits the file size to 5 MB:

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver
      = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(5242880);
    return multipartResolver;
}

3. File Upload Controller

Next, let’s define a controller method that handles the uploading and saving to the server of a file:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(MultipartFile file) throws IOException {
 
    ModelAndView modelAndView = new ModelAndView("file");
    InputStream in = file.getInputStream();
    File currDir = new File(".");
    String path = currDir.getAbsolutePath();
    FileOutputStream f = new FileOutputStream(
      path.substring(0, path.length()-1)+ file.getOriginalFilename());
    int ch = 0;
    while ((ch = in.read()) != -1) {
        f.write(ch);
    }
    
    f.flush();
    f.close();
    
    modelAndView.getModel().put("message", "File uploaded successfully!");
    return modelAndView;
}

If the user attempts to upload a file with a size greater than 5 MB, the application will throw an exception of type MaxUploadSizeExceededException.

4. Handling MaxUploadSizeExceededException

In order to handle this exception, we can have our controller implement the interface HandlerExceptionResolver, or we can create a @ControllerAdvice annotated class.

4.1. Implementing HandlerExceptionResolver

The HandlerExceptionResolver interface declares a method called resolveException() where exceptions of different types can be handled.

Let’s override the resolveException() method to display a message in case the exception caught is of type MaxUploadSizeExceededException:

@Override
public ModelAndView resolveException(
  HttpServletRequest request,
  HttpServletResponse response, 
  Object object,
  Exception exc) {   
     
    ModelAndView modelAndView = new ModelAndView("file");
    if (exc instanceof MaxUploadSizeExceededException) {
        modelAndView.getModel().put("message", "File size exceeds limit!");
    }
    return modelAndView;
}

4.2. Creating a Controller Advice Interceptor

There are a couple of advantages of handling the exception through an interceptor rather than in the controller itself. One is that we can apply the same exception handling logic to multiple controllers.

Another is that we can create a method that targets only the exception we want to handle, allowing the framework to delegate the exception handling without our having to use instanceof to check what type of exception was thrown:

@ControllerAdvice
public class FileUploadExceptionAdvice {
     
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView handleMaxSizeException(
      MaxUploadSizeExceededException exc, 
      HttpServletRequest request,
      HttpServletResponse response) {
 
        ModelAndView modelAndView = new ModelAndView("file");
        modelAndView.getModel().put("message", "File too large!");
        return modelAndView;
    }
}

5. Tomcat Configuration

If you are deploying to Tomcat server version 7 and above, there is a configuration property called maxSwallowSize that you may have to set or change.

This property specifies the maximum number of bytes that Tomcat will “swallow” for an upload from the client when it knows the server will ignore the file.

The default value of the property is 2097152 (2 MB). If left unchanged or if set below the 5 MB limit that we set in our MultipartResolver, Tomcat will reject any attempt to upload a file over 2 MB, and our custom exception handling will never be invoked.

In order for the request to be successful and for the error message from the application to be displayed, you need to set maxSwallowSize property to a negative value. This instructs Tomcat to swallow all failed uploads regardless of file size.

This is done in the TOMCAT_HOME/conf/server.xml file:

<Connector port="8080" protocol="HTTP/1.1"
  connectionTimeout="20000"
  redirectPort="8443" 
  maxSwallowSize = "-1"/>

6. Conclusion

In this article, we have demonstrated how to configure a maximum file upload size in Spring and how to handle the MaxUploadSizeExceededException that results when a client attempts to upload a file exceeding this size limit.

The full source code for this article can be found in the GitHub project.


Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>