File upload using Java

First download Apache Jakarta Commons FileUpload library from this link and add into classpath of your Application.

Validate HTTP Request

Now that you have installed the FileUpload library, you can start writing the code. First, we have to make sure the HTTP request is encoded in multipart format. This can be done using the static method isMultipartContent() of the ServletFileUpload class of the org.apache.commons.fileupload.servlet package:

if (ServletFileUpload.isMultipartContent(request)){
// Parse the HTTP request…

In the above Java code snippet, request is a javax.servlet.http.HttpServletRequest object that encapsulates the HTTP request.

Parsing Form Data

Second, we will parse the form data contained in the HTTP request. Parsing the form data is very straightforward with the Apache Jakarta Commons FileUpload library:

ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List fileItemsList = servletFileUpload.parseRequest(request);

(In the above Java code snippet, DiskFileItemFactory is a class contained in the org.apache.commons.fileupload.disk package and List is an interface contained in the java.util package.)

If everything works fine, fileItemsList will contain a list of file items that are instances of FileItem of the org.apache.commons.fileupload package. A file item may contain an uploaded file or a simple name-value pair of a form field.

By default, the ServletFileUpload instance created by the above Java code uses the following values when parsing the HTTP request:

  • Size threshold = 10,240 bytes. If the size of a file item is smaller than the size threshold, it will be stored in the memory. Otherwise it will be stored in a temporary file on disk.
  • Maximum HTTP request body size = -1, which means the server will accept HTTP request bodies of any size.
  • Repository = System default temp directory, whose value can be found by the Java code System.getProperty(“”). Temporary files will be stored there.

If you do not like the default settings, you can change them using the methods setSizeThreshold() and setRespository() of the DiskFileItemFactory class and the setSizeMax() method of the ServletFileUpload class, like this:

DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

File repositoryPath = new File(“/temp”);

ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(81920); /* the unit is bytes */

If the size of the HTTP request body exceeds the maximum you set, the SizeLimitExceededException exception (fully qualified name: org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException) will be thrown when you call the parseRequest() method:

try {
List fileItemsList = servletFileUpload.parseRequest(request);
/* Process file items… */
catch (SizeLimitExceededException ex) {
/* The size of the HTTP request body exceeds the limit */

Iterating through File Items

Third, we will iterate through the file items and process each of them. The isFormField() method of the FileItem interface is used to determine whether a file item contains a simple name-value pair of a form field or an uploaded file:

Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem);
if (fileItem.isFormField()){
/* The file item contains a simple name-value pair of a form field */
/* The file item contains an uploaded file */

Retrieving Values of Ordinary Form Fields

If a file item contains a simple name-value pair of an ordinary form field, we can retrieve its name and value using the getFieldName() method and the getString() method respectively:

String name = fileItem.getFieldName();
String value = fileItem.getString();

For example, suppose there is a text field in an HTML/XHTML form:

<input name=”text_field” type=”text” />

Getting Information about the Uploaded File

If a file item contains an uploaded file, we can use a number of methods to obtain some information about the uploaded file before we decide what to do with it:

/* Get the name attribute value of the <input type=”file”> element. */
String fieldName = fileItem.getFieldName();

/* Get the size of the uploaded file in bytes. */
long fileSize = fileItem.getSize();

String fileName = fileItem.getName();

String contentType = fileItem.getContentType();

Saving Uploaded Files in the File System

In some situations, you just want to store the uploaded file in the file system without concerning what the uploaded file contains. The FileItem interface provides a method called write() that helps us perform this easily:

File saveTo = new File(“/upload_files/myFile.txt”);

Processing Contents of Uploaded Files

If you do not want to save the uploaded file directly but to process it, then get() and getInputStream() methods can help you. The get() method returns the uploaded file as an array of the byte data type:

byte[] fileData = fileItem.get();

However, if the uploaded file is large in size, you will not want to load the whole file into memory. The getInputStream() method can help you in this case. It returns the uploaded file as a stream:

InputStream fileStream = fileItem.getInputStream();


Related Posts:

One Responses

Free Image Hosting October 10, 2009 at 4:18 am


Comments are closed.