我想限制可以上传到应用程序的文件的大小。为此,我想在上传的文件大小超过限制时从服务器端中止上传过程。
有没有办法在不等待 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 并且可以将错误消息返回或显示回客户端。高温高压
您可以使用 apache commons fileupload 库,该库也允许限制文件大小。