Servlet 3.0 File Upload Handling Exceptions

216 views Asked by At

I am trying to use Java Servlet 3.0 to upload files.

@WebServlet("/uploadFile")
@MultipartConfig(fileSizeThreshold=1024*1024*1,    // 1 MB
                 maxFileSize=1024*1024*10,          // 10 MB
                 maxRequestSize=1024*1024*100)      // 100 MB
public class FileUploadServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String serverUploadDir = getServerUploadDir(req);

    Part file;
    try {
      file = req.getPart("fileName");
      file.write(serverUploadDir + File.separator + file.getSubmittedFileName());
      res.sendRedirect("viewDirectory?msg=File Uploaded.");
    }
    catch (IllegalStateException ex) {
      System.out.println(ex.getMessage());
    }

  }

  public String getServerUploadDir(HttpServletRequest req) {
    return req.getParameter("serverUploadDir");
  }
}

It works correctly, when the files are under the maxFileSize declared in the @MultipartConfig annotation. However, when they are over that size, I get an IllegalStateException and my browser says Connection was Reset. Even if I try to forward the request to a different page in the catch, it doesn't work.

I know with the Spring framework, I can create a filterMultipartResolver and it'll allow me to handle when the maxUploadSize is exceeded. Is there a way to create a regular Java Servlet filter to do the same thing?

0

There are 0 answers