[英]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.