Uploading Files in a Java Servlet

September 10, 2010

I have a need to upload a file via a Java servlet. I've managed to do that using Apache Commons FileUpload, available at http://commons.apache.org/fileupload/.

To upload a file, you need to declare a form field of type file. This must be within a form which is of type multipart/form-data:

<form action="." method="post" enctype="multipart/form-data">
  <input type="file" name="FileToUpload"/>
  <input type="submit" value="Upload File"/>
</form>

The Apache Commons FileUpload code contains an easy way to determine whether the upload is from a multipart form or not:

boolean lIsMultipart = ServletFileUpload.isMultipartContent(pRequest);

Once you have determined this, it is fairly easy to upload the file and read its contents:

if (lIsMultipart)
{
  FileItemFactory lFactory = new DiskFileItemFactory();
  ServletFileUpload lFileUpload = new ServletFileUpload(lFactory);

  try
  {
    List lItems = lFileUpload.parseRequest(pRequest);
    Iterator lIterator = lItems.iterator();

    while (lIterator.hasNext())
    {
      FileItem lItem = (FileItem) lIterator.next();

      if (lItem.isFormField())
      {
        // we have a normal form field
        lResponse.append(lItem.getName() + " = " + lItem.getString() + "\n");
      }
      else
      {
        // we have a file
        lResponse.append("File = " + lItem.getString() + "\n");
      }
    }
  }
  catch (FileUploadException lEx)
  {
    // handle errors processing upload
  }
}

References