Servlet Upload File and Download File Example

File Upload and Download and common tasks in a java web application. Since I have written a lot about java servlet recently, I thought to provide a sample example of file upload and download using servlet.

Use Case

Our use case is to provide a simple HTML page where client can select a local file to be uploaded to server. On submission of request to upload the file, our servlet program will upload the file into a directory in the server and then provide the URL through which user can download the file. For security reason, user will not be provided direct URL for downloading the file, rather they will be given a link to download the file and our servlet will process the request and send the file to user.

We will create a dynamic web project in Eclipse and the project structure will look like below image.


Let’s look into all the components of our web application and understand the implementation.

HTML Page for Uploading File

We can upload a file to server by sending a post request to servlet and submitting the form. We can’t use GET method for uploading file. Another point to note is that enctype of form should be multipart/form-data. To select a file from user file system, we need to use input element with type as file. So we can have a simple HTML page for uploading file as:


<form action="UploadDownloadFileServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName">
<input type="submit" value="Upload">

Server File Location

We need to store file into some directory at server, we can have this directory hardcoded in program but for better flexibility, we will keep it configurable in deployment descriptor context params. Also we will add our upload file html page to the welcome file list.

Our web.xml file will look like below:


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

ServletContextListener implementation

Since we need to read context parameter for file location and create a File object from it, we can write a ServletContextListener to do it when context is initialized. We can set absolute directory location and File object as context attribute to be used by other servlets.

Our ServletContextListener implementation code is like below.

package com.journaldev.servlet;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

public class FileLocationContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
    	String rootPath = System.getProperty("catalina.home");
    	ServletContext ctx = servletContextEvent.getServletContext();
    	String relativePath = ctx.getInitParameter("tempfile.dir");
    	File file = new File(rootPath + File.separator + relativePath);
    	if(!file.exists()) file.mkdirs();
    	System.out.println("File Directory created to be used for storing files");
    	ctx.setAttribute("FILES_DIR_FILE", file);
    	ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		//do cleanup if needed


File Upload Download Servlet Implementation

For File upload, we will use Apache Commons FileUpload utility, for our project we are using version 1.3, FileUpload depends on Apache Commons IO jar, so we need to place both in the lib directory of the project, as you can see that in above image for project structure.

We will use DiskFileItemFactory factory that provides a method to parse the HttpServletRequest object and return list of FileItem. FileItem provides useful method to get the file name, field name in form, size and content type details of the file that needs to be uploaded. To write file to a directory, all we need to do it create a File object and pass it as argument to FileItem write() method.

Since the whole purpose of the servlet is to upload file, we will override init() method to initialize the DiskFileItemFactory object instance of the servlet. We will use this object in the doPost() method implementation to upload file to server directory.

Once the file gets uploaded successfully, we will send response to client with URL to download the file, since HTML links use GET method,we will append the parameter for file name in the URL and we can utilize the same servlet doGet() method to implement file download process.

For implementing download file servlet, first we will open the InputStream for the file and use ServletContext.getMimeType() method to get the MIME type of the file and set it as response content type.

We will also need to set the response content length as length of the file. To make sure that client understand that we are sending file in response, we need to set “Content-Disposition” header with value as “attachment; filename=”fileName“.

Once we are done with setting response configuration, we can read file content from InputStream and write it to ServletOutputStream and the flush the output to client.

Our final implementation of UploadDownloadFileServlet servlet looks like below.

package com.journaldev.servlet;

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadDownloadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private ServletFileUpload uploader = null;
	public void init() throws ServletException{
		DiskFileItemFactory fileFactory = new DiskFileItemFactory();
		File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
		this.uploader = new ServletFileUpload(fileFactory);
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("fileName");
		if(fileName == null || fileName.equals("")){
			throw new ServletException("File Name can't be null or empty");
		File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
			throw new ServletException("File doesn't exists on server.");
		System.out.println("File location on server::"+file.getAbsolutePath());
		ServletContext ctx = getServletContext();
		InputStream fis = new FileInputStream(file);
		String mimeType = ctx.getMimeType(file.getAbsolutePath());
		response.setContentType(mimeType != null? mimeType:"application/octet-stream");
		response.setContentLength((int) file.length());
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

		ServletOutputStream os       = response.getOutputStream();
		byte[] bufferData = new byte[1024];
		int read=0;
		while((read =!= -1){
			os.write(bufferData, 0, read);
		System.out.println("File downloaded at client successfully");

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			throw new ServletException("Content type is not multipart/form-data");

		PrintWriter out = response.getWriter();
		try {
			List<FileItem> fileItemsList = uploader.parseRequest(request);
			Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
				FileItem fileItem =;
				System.out.println("Size in bytes="+fileItem.getSize());

				File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());
				System.out.println("Absolute Path at server="+file.getAbsolutePath());
				out.write("File "+fileItem.getName()+ " uploaded successfully.");
				out.write("<a href=\"UploadDownloadFileServlet?fileName="+fileItem.getName()+"\">Download "+fileItem.getName()+"</a>");
		} catch (FileUploadException e) {
			out.write("Exception in uploading file.");
		} catch (Exception e) {
			out.write("Exception in uploading file.");


The sample execution of the project is shown in below images.




You can download Apache Commons IO jar and Apache Commons FileUpload jar from below URLs.


Incoming search terms:


Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

13 Responses to "Servlet Upload File and Download File Example"

  1. sachin says:

    after uploading the file.
    file could not be downloaded it is showing same uploading window and front of the window it is showing awt_filedownload(no boundle found)

    • Appu says:

      Hi..iwant the after uploading the file that can be visible on the screen and it can edit also…anything is there means send me plz..

  2. uday says:

    It’s showing msg like “Exception in uploading file.”

  3. Aasim says:

    hi want to do same in Net-bean but don’t know to add those Apache Commons FileUpload & io jar file in the project….please help

  4. vincent says:

    I have been trying todo file upload with the above code but am getting some difficults in ubuntu 12.04 running tomacat 6 server. can some help please.

    The following is what i got in log file

    type Exception report


    description The server encountered an internal error () that prevented it from fulfilling this request.


    javax.servlet.ServletException: Servlet execution threw an exception
    root cause

    java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getServletContext()Ljavax/servlet/ServletContext;
    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.35 logs.

  5. jayabalan says:

    FileItem#getName gives the absolute file name including the path, this causes an exception.

  6. Hareesh says:

    Fucking code, doesn’t work waste of time.

  7. hi says:

    hi try this code when u download the file by 3891822

    ResourceBundle rb = ResourceBundle.getBundle(“/iwfweb/resources/ApplicationResources”);
    String filepath = rb.getString(“upload.file.folder.path”);
    System.out.println(rb+filepath+”file store path here”);
    DynaValidatorForm dynaValidatorForm=(DynaValidatorForm)form;
    String fileName = (String) request.getParameter(“fileName”);
    if (fileName != null && !fileName.equals(“”)) {
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;

    try {
    stream = response.getOutputStream();
    File pdf = new File(filepath + fileName);
    if (fileName.indexOf(“.xls”) != -1)
    else if (fileName.indexOf(“.doc”) != -1)

    response.setHeader(“Pragma”, “cache”);
    response.setHeader(“Cache-Control”, “private”);
    response.addHeader(“Content-Disposition”, “attachment; filename=”
    + fileName);
    response.setContentLength((int) pdf.length());
    FileInputStream input = new FileInputStream(pdf);
    buf = new BufferedInputStream(input);
    int readBytes = 0;

    while ((readBytes = != -1)


    } catch (IOException e) {
    //“Exception while downloading template:”+e.getMessage());
    } finally {
    if (stream != null)
    if (buf != null)

  8. Heri says:

    Hi, I ve interested in your tutorial.
    I’m trying to upload to my Virtual Private Server.
    But uploading file rise exception.
    It seems the folder can not be created.
    What do you think? Please share your experience to deploy app in Linux box if you have.

  9. TEM says:

    When uploading exception arises, check and follow the file path being written in the console. Check if all directories exist.

  10. Scott says:

    Anybody have this code? The link is broken

  11. Al says:

    How do I attaché uploaded pdf to email, removing the file when sending email out?

  12. Bhuvana says:

    I need code for uploading the file in db using eclipse. Complete url is not displaying in chrome browser. what to do? how can i get complete url of the file? plsssss..rly if u knw

Leave a Reply

3 + seven =

Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.