servletsjakarta-eemultifile-uploaderapache-commons-fileuploadtomcat10

Error in ServletFileUpload#parseRequest(request) with tomcat 10


Working on a simple file upload program. I had to use jakarta.servlet.* classes as I am using Tomcat v10. I am getting compile time error on parseRequest(request) line.

Code :

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
        try {
            List<FileItem> multifiles = sf.parseRequest(request);
            
            for(FileItem i : multifiles) {
                i.write(new File("C:/Users/Luffy/Documents/FileUploadDemo/"+i.getName()));
            }
            response.getWriter().print("The file is uploaded");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        response.getWriter().print("The file is uploaded");
    }

The error is as below:

The method parseRequest(javax.servlet.http.HttpServletRequest) in the type ServletFileUpload is not applicable for the arguments (jakarta.servlet.http.HttpServletRequest)

I searched a lot on google but couldn't find a solution.

Please suggest a workaround or possible solution. Thanks in advance.

This is my first post in Stack overflow. So ignore my mistakes if any :)


Solution

  • You are trying to use the ServletFileUpload class from commons-fileupload, which doesn't work with a jakarta.servlet.http.HttpServletRequest. The library must be adapted to work with Servlet 5.0 classes.

    Fortunately since Servlet 3.0 (Tomcat 8.0) multipart/form-data requests can be parsed by the servlet. You just need to:

    try {
        final Collection<Part> parts = request.getParts();
        for (final Part part : parts) {
           part.write("C:/Users/Luffy/Documents/FileUploadDemo/"+part.getSubmittedFileName());
        }
        response.getWriter().print("The file has been uploaded successfully.");
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Upload failed.");
    }