Java 如何处理MaxUploadSizeExceedeException
Java 如何处理MaxUploadSizeExceedeException,java,spring,forms,file-upload,spring-mvc,Java,Spring,Forms,File Upload,Spring Mvc,maxUploadSizeExceedeExceptionexception当我上载的文件大小超过允许的最大值时,会出现异常。我想在出现此异常时显示一条错误消息(如验证错误消息)。在Spring3中,我如何处理这个异常来执行类似的操作 谢谢。我终于想出了一个使用HandlerExceptionResolver的解决方案 将多部分解析器添加到Spring配置中: <bean id="multipartResolver" class="org.springframework.web.multi
maxUploadSizeExceedeException
exception当我上载的文件大小超过允许的最大值时,会出现异常。我想在出现此异常时显示一条错误消息(如验证错误消息)。在Spring3中,我如何处理这个异常来执行类似的操作
谢谢。我终于想出了一个使用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>
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;
}
}
<%@ 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>
查看-/upload.jsp:
<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>
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;
}
}
<%@ 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>
测试文件上传
选择要上载的文件
${errors}。
标题:
文件:
控制器-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);
}
}
========================================================================
import java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.HashMap;
导入java.util.Map;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入org.springframework.stereotype.Controller;
导入org.springframework.ui.Model;
导入org.springframework.validation.BindingResult;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入org.springframework.web.multipart.maxUploadSizeExceedeException;
导入org.springframework.web.servlet.HandlerExceptionResolver;
导入org.springframework.web.servlet.ModelAndView;
导入com.mypkg.models.UploadedFile;
@控制器
公共类FileUploadController实现HandlerExceptionResolver
{
@RequestMapping(value=“/upload”,method=RequestMethod.GET)
公共字符串getUploadForm(模型)
{
addAttribute(“uploadedFile”,newUploadedFile());
返回“/上传”;
}
@RequestMapping(value=“/upload”,method=RequestMethod.POST)
创建公共字符串(UploadedFile UploadedFile,BindingResult)
{
//对这个文件做些什么
System.out.println(“+uploadedFile.getTitle());
System.out.println(“创建本地文件:/var/test file upload/”+uploaded file.getFileData().getOriginalFilename());
尝试
{
InputStream in=uploadedFile.getFileData().getInputStream();
FileOutputStream f=新的FileOutputStream(
“/var/test file upload/”+uploadedFile.getFileData().getOriginalFilename());
int ch=0;
而((ch=in.read())!=-1)
{
f、 写入(ch);
}
f、 冲洗();
f、 close();
}
捕获(IOE异常)
{
e、 printStackTrace();
}
返回“重定向:/”;
}
/***在上载过程中捕获异常并在视图表单中显示错误***/
公共模型和视图解析异常(HttpServletRequest请求,
HttpServletResponse,对象处理程序,异常)
{
映射模型=新的HashMap();
if(MaxUploadSizeExceedeException的异常实例)
{
model.put(“errors”,exception.getMessage());
}否则
{
model.put(“错误”,“意外错误:”+exception.getMessage());
}
put(“uploadedFile”,newuploadedfile());
返回新的ModelAndView(“/upload”,model);
}
}
========================================================================
感谢您解决此问题。我忙了好几个小时想解决这个问题
关键是让控制器实现HandlerExceptionResolver
并添加resolveException
方法
--Bob使用控制器建议
@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;
}
}
如果使用ajax,需要响应json,可以在resolveException方法中响应json
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
ModelAndView view = new ModelAndView();
view.setView(new MappingJacksonJsonView());
APIResponseData apiResponseData = new APIResponseData();
if (ex instanceof MaxUploadSizeExceededException) {
apiResponseData.markFail("error message");
view.addObject(apiResponseData);
return view;
}
return null;
}
这是一个老生常谈的问题,所以我为未来的人们(包括未来的我)添加了这个问题,他们正在努力使Spring Boot 2能够正常工作
首先,您需要配置spring应用程序(在属性文件中):
如果您使用的是嵌入式Tomcat(很可能是,因为它是标准的),那么配置Tomcat以避免取消具有大型主体的请求也很重要
server.tomcat.max-swallow-size=-1
或者至少将其设置为相对较大的尺寸
server.tomcat.max-swallow-size=100MB
如果您不为Tomcat设置MaxThanksize,您可能会浪费大量时间调试为什么会处理错误,但浏览器不会得到响应-这是因为没有此配置,Tomcat将取消请求,即使您在日志中看到应用程序正在处理错误,浏览器已经收到来自Tomcat的取消请求,并且不再侦听响应
要处理MaxUploadSizeExceedeException,您可以使用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:/"
}
}
注意:如果要在控制器类中直接使用ExceptionHandler处理MaxUploadSizeExceedeException,则应配置以下属性:
spring.servlet.multipart.resolve-lazily=true
否则,将在请求映射到控制器之前触发该异常。通过在Java中捕获异常并显示错误页面?@skaffman我更愿意返回表单页面并在那里显示错误,但是异常在到达填充模型属性的控制器之前被抛出。请看一下HandlerExceptionResolver:我也在处理这个问题。但是,我发现请求中没有填充任何其他参数,即使它们在我的表单中