Search code examples
javajakarta-eeservletsuploadapache-commons

Unable to use ApacheCommons for fileupload if I annotate the servlet with MultipartConfig


If I annotate the following servlet with @MultipartConfig ,I am unable to use Apache common upload .

@MultipartConfig

public class SendTheFileName extends HttpServlet {
  // something
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
           moveToSharedDirectory(request,path); // call to upload
  }
}

For example :

public boolean moveToSharedDirectory(HttpServletRequest request,String path) {
    System.out.println("1. OUTSIDE THE TRY BLOCK OF UPLOAD CLASS");
    try {
       System.out.println("2. IN THE TRY BLOCK OF UPLOAD CLASS");
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       System.out.println("3. AFTER THE BOOLEAN STATEMENT " + isMultipart);
       if(!isMultipart) {
           // Error:File cannot be uploaded
           System.out.println("Message : IS NOT MULTIPART");
       } else {
           DiskFileItemFactory dfif = new DiskFileItemFactory();
           ServletFileUpload fileUpload = new ServletFileUpload(dfif);
           List list = null;
           list = fileUpload.parseRequest(request); // returns a list of FileItem instances parsed from the request
           Iterator iterator = list.iterator();
           System.out.println("4. JUST BEFORE ENTERING THE WHILE LOOP");
           System.out.println("5. CHECKING IF THE ITERATION HAS ANY ELEMENT : " + iterator.hasNext());

           // ... some more here {-}
         }
    } // close catch
} 

The statement in the just above snippet :

System.out.println("5. CHECKING IF THE ITERATION HAS ANY ELEMENT : " + iterator.hasNext());

prints false! Why is that ?

If I remove the annotation I get true and am able to upload the file.

Corresponding HTML :

<form method="post" action="SendTheFileName" enctype="multipart/form-data">
                <div id="Files_to_be_shared"> 
                      <input type="file" id="File" name="FileTag" />
                      <input type="submit" value="Share" /> 
                    </div>
 </form>

Note: For some reason I had to use apache commons to upload the file.


Solution

  • The @MultipartConfig triggers Servlet 3.0 builtin multipart/form-data request body parsing right before the servlet's service() is invoked. So the Apache Commons FileUpload would face an empty request body when it's its turn to parse the request. In other words, you can't mix them. It does also not make any sense to mix them as they both do exactly same job under the covers.

    You have 2 options:

    1. Remove @MultipartConfig and keep Apache Commons FileUpload.

    2. Or, keep @MultipartConfig and remove Apache Commons FileUpload.

    See also: