Aborting upload from a servlet to limit file size(中止从 servlet 上传以限制文件大小)
问题描述
我想限制可以上传到应用程序的文件大小.为了实现这一点,我想在上传的文件大小超过限制时从服务器端中止上传过程.
I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.
有没有办法在不等待 HTTP 请求完成的情况下从服务器端中止上传过程?
Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?
推荐答案
你可以这样做(使用 Commons 库):
You can do something like this (using the Commons library):
public class UploadFileServiceImpl extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
try
{
FileItem uploadItem = getFileItem(request);
if (uploadItem == null)
{
// ERROR
}
// Add logic here
}
catch (Exception ex)
{
response.getWriter().write("Error: file upload failure: " + ex.getMessage());
}
}
private FileItem getFileItem(HttpServletRequest request) throws FileUploadException
{
DiskFileItemFactory factory = new DiskFileItemFactory();
// Add here your own limit
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
ServletFileUpload upload = new ServletFileUpload(factory);
// Add here your own limit
upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
List<?> items = upload.parseRequest(request);
Iterator<?> it = items.iterator();
while (it.hasNext())
{
FileItem item = (FileItem) it.next();
// Search here for file item
if (!item.isFormField() &&
// Check field name to get to file item ...
{
return item;
}
}
return null;
}
}
这篇关于中止从 servlet 上传以限制文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:中止从 servlet 上传以限制文件大小
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01