file uploading example of servlet

In this post, you will learn:

  • How to upload a file using a servlet?
  • What is a multipart request?
  • Use of Apache commons file upload API?

Steps required to upload a file:

1. In html form, request type is set to post and enctype is set to multipart/form-data.

2. <input type=”file” > element is used in the html form to facilitate selection of the file from the file system.

3. In the servlet multi part request is parsed to obtain file and other form field information.

4. File contents are saved on the server.

How to process a multi part request in a servlet?

Before Servlet 3 API, there was no direct support for processing multi part requests in a servlet. Third party APIs were required for uploading file. Various third party APIs are available such as Apache commons file upload API, Struts File Upload API etc. In this example, I am using Apache commons file upload API for processing multi part request. Another example of file upload will be provided later using servlet 3 API when Servlet 3 anotations will be covered.

Understanding multi part request processing using Apache commons file upload API:

A file upload request comprises an ordered list of items that are encoded according to RFC 1867, “Form-based File Upload in HTML”. Apache commons file upload API provides FileUpload class for parsing such a requests. For each uploaded item, FileUpload returns a FileItem object. A FileItem object holds the uploaded item information such as type, name, contentType etc.

FileUpload is high levle class and ServletFileUpload is its subclass which is used in servlet environment. A FileUpload object uses a FileItemFactory object for creating FileItem objects. FileItemFactory is an interface and DiskFileItemFactory is one of its implementation. It creates file items for disk files.

Steps required to process a multi part request using Apache commons file upload API:

1. Check whether a request contains multi part form data or not. ServletFileUpload class provides following method for this purpose.

public static boolean isMultipartContent(HttpServletRequest request);

2. If request contains multi part form data then create a DiskFileFactory object using the default constructor.

public DiskFileFactory();

3. Set upload folder path to the DiskFileFactory, using the following method.

public void setRepository(File repository);

4. Create a ServletFileUpload object using the following constructor.

public ServletFileUpload(FileItemFactory factory);

5. Set max size limit for the uploaded file using the following method of FileUpload.

public void setFileSizeMax(long maxSize);

6. Parse the multi part request using the following method of ServletFileUpload.

public List<FileItem> parseRequest(HttpServletRequest request);

7. Iterate the list and in each iteration check whether FileItem object represents a form field using the following method of FileItem.

public boolean isFormField();

8. If FileItem is a form field then read its value using the following method of FileItem.

public String getString();

9. If FileItem represents a file then save it on the server using the following method of FileItem.

public void write(File file) throws Exception;

10. To obtain file name and size use the following methods of FileItem.

public String getName();

public long getSize();

Practical example of file uploading:

First, the index.html :

<form method="post" action="uploaderServlet" enctype="multipart/form-data">
Name: <input type="text" name="name"><br/>
Profile Image:<input type="file" name="toBeUploaded"><br/>
<input type="submit" value="Submit">			   

Second the UploaderServlet. This servlet assumes that uploaded files will be saved in a folder named uploads which is under WEB-INF/classes. If you are using an IDE such as eclipse, then create this folder under src.

package com.techmentro.learningpad;

import java.util.Iterator;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploaderServlet extends HttpServlet
	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response)
		PrintWriter out=null;
			String name=null;
        //Request is multipart, process it.
//obtain the path of the upload folder which is assumed to be under WEB-INF/classes folder
		String path=getServletConfig().getServletContext().getRealPath("WEB-INF/classes/uploads");
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		//Set the upload folder
		factory.setRepository(new File(path));

		// Create a new file upload handler using the factory
		ServletFileUpload upload = new ServletFileUpload(factory);
		// Parse the request
		List<FileItem> items = upload.parseRequest(request);
		Iterator<FileItem> itr =items.iterator();
            FileItem fileItem =;
            	//FileItem is a form field read its value.
            	name=fileItem.getString();//we have only field name.
            	 //FileItem is file, process it.
            	//A File object is created for the file  
                File file = new File(path+File.separator+fileItem.getName());
                //uploaded contents are saved to the file.
                out.write(name+ ", your profile image of size "+getSizeString(fileItem.getSize())+" is uploaded successfully.");
		//Request is not multi part, throw an exception.	
		throw new ServletException("Content type must be multipart/form-data");
		}catch(Exception ex)
//utility method created to obtain file size in MB, KB and Bytes.	
public String getSizeString(float sizeInBytes)
		return sizeInBytes+" Bytes";
	else if(sizeInBytes <1024*1024)
		return sizeInBytes/1024+" KB";
		return sizeInBytes/1024*1024+" MB";

Third, the web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">

Output screen images of the practical example:

The first screen represents the home page generated by index.html. It contains input form through which user submits his name and profile image.


The second screen represents the response of the uploaderServlet when the file is successfully uploaded.


The third screen represents the input form when user select a file having size greater than the upload limit set by the uploaderServlet.


The fourth screen represents the exception generated by the uploaderServlet when the size of uploaded file is greater than the size limit.


To execute this example, commons-fileupload-xx.jar and commons-io-xx.jar files are required. Both of these jar files are stored in the lib folder of the application zip file which is available for download.

Its time to recap the main concepts:

  1. A post request is sent having enctype="multipart/form-data" for uploading a file.
  2. <input type="file" > html element is used to facilitate selection of the file from the file system.
  3. In the servlet multi part request is processed and file is saved on the server.
  4. For processing multi part request, A thid party API such as Apache commons file upload is used.

Example Source Code

If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *