MaxUploadSizeExceededException in Spring – Spring中的MaxUploadSizeExceededException

最后修改: 2017年 1月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

在Spring框架中,当应用程序试图上传一个大小超过配置中指定的某个阈值的文件时,会抛出一个MaxUploadSizeExceededException

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

2.设置最大上传尺寸

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.

默认情况下,对可以上传的文件的大小没有限制。为了设置最大的上传尺寸,你必须声明一个MultipartResolver类型的bean。

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

让我们看一个将文件大小限制在5MB的例子。

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

3. File Upload Controller

3.文件上传控制器

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.

如果用户试图上传一个大小超过5MB的文件,应用程序将抛出一个MaxUploadSizeExceededException类型的异常。

4. Handling MaxUploadSizeExceededException

4.处理MaxUploadSizeExceededException

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

为了处理这个异常,我们可以让我们的控制器实现HandlerExceptionResolver接口,或者我们可以创建一个@ControllerAdvice注释的类。

4.1. Implementing HandlerExceptionResolver

4.1.实现HandlerExceptionResolver

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

HandlerExceptionResolver接口声明了一个名为resolveException()的方法,不同类型的异常都可以被处理。

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

让我们重写resolveException()方法,以便在捕获的异常是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

4.2.创建一个控制器建议拦截器

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:

另一个是,我们可以创建一个只针对我们想要处理的异常的方法,允许框架委托异常处理,而不需要我们使用instanceof来检查抛出的异常是什么类型。

@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

5.Tomcat配置

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.

如果你部署到Tomcat服务器7及以上版本,有一个名为maxSwallowSize的配置属性,你可能需要设置或更改。

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.

为了使请求成功并显示应用程序的错误信息,你需要将maxSwallowSize属性设置为一个负值。这指示Tomcat吞下所有失败的上传,无论文件大小如何。

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

这在TOMCAT_HOME/conf/server.xml文件中完成。

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

6. Conclusion

6.结论

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.

在这篇文章中,我们演示了如何在Spring中配置最大的文件上传尺寸,以及如何处理当客户端试图上传超过该尺寸限制的文件时产生的MaxUploadSizeExceededException

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

本文的完整源代码可以在GitHub项目中找到。