MaxUploadSizeExceededException in Spring – Spring中的MaxUploadSizeExceededException

最后修改: 2017年 1月 28日


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:


public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver
      = new CommonsMultipartResolver();
    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 = != -1) {
    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:


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:


public class FileUploadExceptionAdvice {
    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.

此属性指定了Tomcat在知道服务器会忽略文件时,从客户端 “吞下 “上传的最大字节数。

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.

该属性的默认值是2097152(2 MB)。如果保持不变,或者设置低于我们在MultipartResolver中设置的5MB限制,Tomcat将拒绝任何超过2MB的文件上传尝试,而我们的自定义异常处理将永远不会被调用。

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"
  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.