Java 如何处理 MaxUploadSizeExceededException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2689989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:52:26  来源:igfitidea点击:

How to handle MaxUploadSizeExceededException

javaspringformsfile-uploadspring-mvc

提问by Javi

MaxUploadSizeExceededExceptionexception appears when I upload a file whose size exceeds the maximum allowed. I want to show an error message when this exception appears (like a validation error message). How can I handle this exception to do something like this in Spring 3?

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

Thanks.

谢谢。

采纳答案by Steve Davis

I finally figured out a solution that works using a HandlerExceptionResolver.

我终于找到了一个使用 HandlerExceptionResolver 的解决方案。

Add multipart resolver to your Spring config:

将多部分解析器添加到您的 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>   

Model - UploadedFile.java:

模型 - 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;
    }

}

View - /upload.jsp:

查看 - /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>

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

控制器 - FileUploadController.java: 包 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);
    }

}

========================================================================

回答by BobC

Thanks for solving this Steve. I banged around trying to solve for several hours.

感谢您解决这个史蒂夫。我试图解决几个小时。

The key is to have the controller implement HandlerExceptionResolverand add the resolveExceptionmethod.

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

--Bob

--鲍勃

回答by Jonghee Park

Use controller advice

使用控制器建议

@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 MappingHymansonJsonView());
            mav.addObject("result", "nok");
        }
        else mav.setViewName("uploadError");
        return mav;
    }
}

回答by Mr Lou

if using ajax,need to response json,can response json in resolveException method

如果使用ajax,需要响应json,可以在resolveException方法中响应json

@Override
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    ModelAndView view = new ModelAndView();
    view.setView(new MappingHymansonJsonView());
    APIResponseData apiResponseData = new APIResponseData();

    if (ex instanceof MaxUploadSizeExceededException) {
      apiResponseData.markFail("error message");
      view.addObject(apiResponseData);
      return view;
    }
    return null;
  }

回答by AbstractVoid

This is an old question so I'm adding it for the future people (including future me) who are struggling to get this working with Spring Boot 2.

这是一个老问题,所以我将它添加给正在努力使用Spring Boot 2的未来人(包括未来的我)。

At first you need to configure the spring application (in properties file):

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

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

If you're using embedded Tomcat (and most likely you are, as it comes as standard) it's also important to configure Tomcat not to cancel the request with large body

如果您使用的是嵌入式 Tomcat(并且很可能是,因为它是标准配置),配置 Tomcat 以不取消大正文请求也很重要

server.tomcat.max-swallow-size=-1

or at least set it to relatively big size

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

server.tomcat.max-swallow-size=100MB

If you will not set maxSwallowSize for Tomcat, you might waste lots of hours debugging why the error is handled but browser gets no response - that's because without this configuration Tomcat will cancel the request, and even though you'll see in the logs that application is handling the error, the browser already received cancellation of request from Tomcat and isn't listening for the response anymore.

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

And to handle the MaxUploadSizeExceededExceptionyou can add ControllerAdvicewith ExceptionHandler.

为了处理MaxUploadSizeExceededException,您可以使用ExceptionHandler添加ControllerAdvice

Here's a quick example in Kotlin that simply sets a flash attribute with an error and redirects to some page:

这是 Kotlin 中的一个简单示例,它简单地设置了一个带有错误的 flash 属性并重定向到某个页面:

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

NOTE: if you want to handle MaxUploadSizeExceededException with ExceptionHandler directly in your controller class, you should configure following property:

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

spring.servlet.multipart.resolve-lazily=true

otherwise that exception will be triggered before the request is mapped to controller.

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