Aborting upload from a servlet to limit file size

前端 未结 4 1657
余生分开走
余生分开走 2020-12-18 07:03

I\'d like to limit the size of the file that can be uploaded to an application. To achieve this, I\'d like to abort the upload process from the server side when the size of

4条回答
  •  青春惊慌失措
    2020-12-18 07:43

    You can do something like this (using the Commons library):

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

提交回复
热议问题