[英]Is there a reliable way to limit the size of a file upload via java servlet?
[英]Aborting upload from a servlet to limit file size
我想限制可以上传到应用程序的文件的大小。 为了实现这一点,我想在上传文件的大小超过限制时从服务器端中止上传过程。
有没有办法在不等待HTTP请求完成的情况下从服务器端中止上传过程?
使用JavaEE 6 / Servlet 3.0,首选方法是在servlet上使用@MultipartConfig注释 ,如下所示:
@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class UploadFileServiceImpl extends HttpServlet ...
你可以这样做(使用Commons库):
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的doPost()方法中执行此操作
multi = new MultipartRequest(request, dirName, FILE_SIZE_LIMIT);
if(submitButton.equals(multi.getParameter("Submit")))
{
out.println("Files:");
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String)files.nextElement();
String filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
File f = multi.getFile(name);
if (f.length() > FILE_SIZE_LIMIT)
{
//show error message or
//return;
return;
}
}
这样您就不必等待完全处理HttpRequest并返回或向客户端显示错误消息。 HTH
你可以使用apache commons fileupload库,这个库也允许你的文件大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.