从servlet中止上传限制文件大小(Aborting upload from a servlet

2019-08-18 06:43发布

我想限制可以上传到应用程序的文件的大小。 要做到这一点,我想从服务器端中止上传过程中,当被上传文件的大小超过了限制。

有没有办法中止从服务器端的上传过程,而不必等待HTTP请求完成?

Answer 1:

你可以做这样的事情(使用共享库):

    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;
        }
    }


Answer 2:

随着JavaEE的6 / Servlet的3.0这样做的最佳方法是使用@MultipartConfig标注上你的servlet是这样的:

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, 
    maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class UploadFileServiceImpl extends HttpServlet ...


Answer 3:

你可以在你的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



Answer 4:

您可以使用Apache通用FileUpload库,这个库许可证limir文件的大小也。

http://commons.apache.org/fileupload/



文章来源: Aborting upload from a servlet to limit file size