如何处理MaxUploadSizeExceededException

Jav*_*avi 28 java forms spring file-upload spring-mvc

MaxUploadSizeExceededException当我上传大小超过允许的最大值的文件时,会出现异常.我想在出现此异常时显示错误消息(如验证错误消息).如何在Spring 3中处理此异常以执行此类操作?

谢谢.

小智 33

我终于想出了一个使用HandlerExceptionResolver工作的解决方案.

将多部分解析器添加到Spring配置:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
   <!--  the maximum size of an uploaded file in bytes -->
   <!-- <property name="maxUploadSize" value="10000000"/> -->
   <property name="maxUploadSize" value="1000"/>
</bean>   
Run Code Online (Sandbox Code Playgroud)

Model - UploadedFile.java:

package com.mypkg.models;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadedFile
{
    private String title;

    private CommonsMultipartFile fileData;

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public CommonsMultipartFile getFileData()
    {
        return fileData;
    }

    public void setFileData(CommonsMultipartFile fileData)
    {
        this.fileData = fileData;
    }

}
Run Code Online (Sandbox Code Playgroud)

查看 - /upload.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Test File Upload</title>
    </head>
    <body>
        <h1>Select a file to upload</h1>
        <c:if test="${not empty errors}">
            <h2 style="color:red;">${errors}.</h2>
        </c:if>
        <form:form modelAttribute="uploadedFile" method="post" enctype="multipart/form-data" name="uploadedFileform" id="uploadedFileform">
            <table width="600" border="0" align="left" cellpadding="0" cellspacing="0" id="pdf_upload_form">
                <tr>
                    <td width="180"><label class="title">Title:</label></td>
                    <td width="420"><form:input id="title" path="title" cssClass="areaInput" size="30" maxlength="128"/></td>
                </tr>
                <tr>
                    <td width="180"><label class="title">File:</label></td>
                    <td width="420"><form:input id="fileData" path="fileData" type="file" /></td>
                 </tr>
                 <tr>
                    <td width="180"></td>
                    <td width="420"><input type="submit" value="Upload File" /></td>
                 </tr>
            </table>
        </form:form>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Controller - FileUploadController.java:package com.mypkg.controllers;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.mypkg.models.UploadedFile;

@Controller
public class FileUploadController  implements HandlerExceptionResolver
{
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String getUploadForm(Model model)
    {
        model.addAttribute("uploadedFile", new UploadedFile());
        return "/upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String create(UploadedFile uploadedFile, BindingResult result)
    {
        // Do something with the file
        System.out.println("#########  File Uploaded with Title: " + uploadedFile.getTitle());
        System.out.println("#########  Creating local file: /var/test-file-upload/" + uploadedFile.getFileData().getOriginalFilename());

        try
        {

            InputStream in = uploadedFile.getFileData().getInputStream();
            FileOutputStream f = new FileOutputStream(
                    "/var/test-file-upload/" + uploadedFile.getFileData().getOriginalFilename());
            int ch = 0;
            while ((ch = in.read()) != -1)
            {
                f.write(ch);
            }
            f.flush();
            f.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return "redirect:/";
    }

    /*** Trap Exceptions during the upload and show errors back in view form ***/
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception exception)
    {        
        Map<String, Object> model = new HashMap<String, Object>();
        if (exception instanceof MaxUploadSizeExceededException)
        {
            model.put("errors", exception.getMessage());
        } else
        {
            model.put("errors", "Unexpected error: " + exception.getMessage());
        }
        model.put("uploadedFile", new UploadedFile());
        return new ModelAndView("/upload", model);
    }

}

========================================================================
Run Code Online (Sandbox Code Playgroud)

  • 我试图将相同的方法付诸实践,但没有任何效果.也尝试了与[post](http://www.raistudies.com/spring/spring-mvc/file-upload-spring-mvc-annotation/)中提到的相同的方法.即使发生异常,也不会调用`resolveException()`方法.我想在同一页面上显示用户友好的错误消息,但我在网页上获得完整的堆栈跟踪.我错过了Spring 3.2.0的一些东西吗? (6认同)
  • 如果所有控制器都实现了这个HandlerExceptionResolver,那么当异常发生时它们都将被调用? (4认同)

Bob*_*obC 7

谢谢你解决这个史蒂夫.我试图解决几个小时的问题.

关键是让控制器实现HandlerExceptionResolver并添加resolveException方法.

--Bob

  • 最好的!我正要关闭这个标签,但后来发现了这个!谢谢! (2认同)

Wal*_*rer 6

这是一个古老的问题,因此我将其添加到正在努力使之与Spring Boot 2兼容的未来人们(包括未来我)中。

首先,您需要配置spring应用程序(在属性文件中):

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
Run Code Online (Sandbox Code Playgroud)

如果您使用的是嵌入式Tomcat(并且很可能是标准配置),那么配置Tomcat使其不取消大型请求也很重要。

server.tomcat.max-swallow-size=-1
Run Code Online (Sandbox Code Playgroud)

或至少将其设置为相对较大的尺寸

server.tomcat.max-swallow-size=100MB
Run Code Online (Sandbox Code Playgroud)

如果您不为Tomcat设置maxSwallowSize,则可能会浪费大量时间来调试为什么会处理错误,但浏览器却没有响应-这是因为没有此配置,Tomcat将会取消请求,即使您在日志中看到该应用程序正在处理错误,浏览器已经收到Tomcat的取消请求,并且不再侦听响应。

为了处理MaxUploadSizeExceededException,可以添加带有ExceptionHandler的ControllerAdvice

这是Kotlin中的一个简单示例,该示例简单地将Flash属性设置为错误并重定向到某些页面:

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

注意:如果要直接在控制器类中使用ExceptionHandler处理MaxUploadSizeExceededException,则应配置以下属性:

spring.servlet.multipart.resolve-lazily=true
Run Code Online (Sandbox Code Playgroud)

否则,将在请求映射到控制器之前触发该异常。

  • 太感谢了。这正是我浪费上午时间的事情!开门见山。 (3认同)
  • spring.servlet.multipart.resolve-lazily 属性确实很有帮助。谢谢! (2认同)
  • 您应该获得一枚金牌,并将其标记为正确答案。 (2认同)
  • 谢谢你,我喜欢 Kotlin,你的解决方案非常聪明,非常感谢 (2认同)

Jon*_*ark 5

使用控制器建议

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView handleMaxUploadException(MaxUploadSizeExceededException e, HttpServletRequest request, HttpServletResponse response){
        ModelAndView mav = new ModelAndView();
        boolean isJson = request.getRequestURL().toString().contains(".json");
        if (isJson) {
            mav.setView(new MappingJacksonJsonView());
            mav.addObject("result", "nok");
        }
        else mav.setViewName("uploadError");
        return mav;
    }
}
Run Code Online (Sandbox Code Playgroud)