简体   繁体   中英

How to limit uploaded file size in java servlet

I need to upload an image from client to server using html type='file' which works fine,so far I could is to send file from client and receive on my servlet, but now I need to limit the image size in my servlet upto 2MB and if it's bigger than 2MB I need to send an error to client saying about the image size.

Here my servlet code that I receive sent image:

public void doPost(HttpServletRequest request, 
      HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    MultipartRequest multipartRequest = new MultipartRequest(request, "D:\\");
    out.print("Successfully Uploaded");
}

so far it does is to receive image and save it in D: directory, and I don't want to first save the image and then check image size, but to say something to MultipartRequest that if you received higher than 2MB send an error.

Thanks in advance:)

Since you haven't specified what is "MultipartRequest" class, I assume you are using oreilly package.

It has a public MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) throws IOException constructor, which takes max file size parameter.

If the uploaded file size is more than maxPostSize, it will throw an IOException. You could probably catch this exception and return error response.

You can restrict the size of the uploaded file when creating a MultipartRequest instance.

  • MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory)

Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to the given directory, and limiting the upload size to 1 Megabyte.

  • MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory, int maxPostSize)

Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to the given directory, and limiting the upload size to the specified length.

Use this code on servlet and try it now

  private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ; `

DiskFileItemFactory factory = new DiskFileItemFactory();


      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);

      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);

      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try { 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");  
         out.println("</head>");
         out.println("<body>");

         while ( i.hasNext () ) {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) {
               // Get the uploaded file parameters
               String fieldName = fi.getFieldName();
               String fileName = fi.getName();
               String contentType = fi.getContentType();
               boolean isInMemory = fi.isInMemory();
               long sizeInBytes = fi.getSize();

               // Write the file
               if( fileName.lastIndexOf("\\") >= 0 ) {
                  file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
               } else {
                  file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
               }
               fi.write( file ) ;
               out.println("Uploaded Filename: " + fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
         } catch(Exception ex) {
            System.out.println(ex);
         }

file size is in bytes form so u can add max file size according to your requirements bytes to mb thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM