gpt4 book ai didi

java - 如何处理 MaxUploadSizeExceededException : Maximum upload in servlet

转载 作者:搜寻专家 更新时间:2023-11-01 03:52:31 25 4
gpt4 key购买 nike

我发现 Apache Tomcat 允许以下配置,采用硬编码或注释方法。我不确定最大文件大小是在上传过程中还是在文件上传到临时位置之后计算的。该文档指示以下内容:

The @MultipartConfig annotation supports the following optional attributes:

location: An absolute path to a directory on the file system. The location attribute does not support a path relative to the application context. This location is used to store files temporarily while the parts are processed or when the size of the file exceeds the specified fileSizeThreshold setting. The default location is "".

fileSizeThreshold: The file size in bytes after which the file will be temporarily stored on disk. The default size is 0 bytes.

MaxFileSize: The maximum size allowed for uploaded files, in bytes. If the size of any uploaded file is greater than this size, the web container will throw an exception (IllegalStateException). The default size is unlimited.

maxRequestSize: The maximum size allowed for a multipart/form-data request, in bytes. The web container will throw an exception if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.

注释方法:

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, 
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

如果有人能澄清上传过程中是否计算了 MaxFileSize 以及如何在 servlet 中处理此异常,我将不胜感激。

最佳答案

如果正在上传的文件大小超过配置的最大值,将抛出一个IllegalStateException异常。

当您尝试通过调用 HttpServletRequest.getParts() 来获取请求的部分时,就会发生这种情况。或 HttpServletRequest.getPart() .所以最简单的方法就是简单地将其放入 try-catch block 中,如下所示:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

Parts parts = null
try {
parts = request.getParts();
} catch (IllegalStateException e) {
// File or request is too big!
// Here you can send back an error message to the client,
// I just send back an HTTP 400 (Bad Request) error page.
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}

// Process parts...
}

关于java - 如何处理 MaxUploadSizeExceededException : Maximum upload in servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21573450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com