我想限制可以上传到应用程序的文件的大小。为实现这一目标,当上传文件的大小超过限制时,我想从服务器端中止上传过程。
有没有办法在不等待HTTP请求完成的情况下从服务器端中止上传过程?
答案 0 :(得分:3)
使用JavaEE 6 / Servlet 3.0,首选方法是在servlet上使用@MultipartConfig annotation,如下所示:
@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class UploadFileServiceImpl extends HttpServlet ...
答案 1 :(得分:2)
您可以执行以下操作(使用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;
}
}
答案 2 :(得分:1)
您可以尝试在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
答案 3 :(得分:1)
您可以使用apache commons fileupload库,此库也允许限制文件大小。