File Upload in JAVA Using Apache Commons API


In this post we are going to learn how to upload files to the server. There are several APIs available to perform this operation in JAVA. Here I have given an example of file upload application using Apache’s commons libraries. Servlet 3.0 provides its own API for file uploading, but we will see all the above methods in later posts.

Resources required:

Project Structure:
File Upload in JAVA Using Apache Commons API Folder Structure

This is the home page of the application. In this file we have a form having a file type input field. For file uploading the ‘enctype’ attribute of the <form> tag should be ‘multipart/form-data’.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>File Uploader Example</title>
	<form method="post" action="uploadServlet" enctype="multipart/form-data">
	Select file to upload:
	<input type="file" name="uploadFile" />
	<input type="submit" value="Upload" />

This is the deployment descriptor of the application, where we have given entry for the servlet that is going to handle the file upload request and the welcome file i.e. the home page of the application.

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




This is the servlet where using Apache’s commons API we are saving the file to the server’s directory. For file upload the request must be of multipart type. So first we are checking whether the request is multipart or not by using the following line.

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

ServletFileUpload is the class available in commons-fileupload JAR file. The method isMultipartContent() returns true if the request is multipart else returns false. So when it is false we are redirecting to the home page with an error message. If true, we are proceeding with the uploading process.

package com.fileuploader.servlet;

import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

 * Servlet implementation class UploaderServlet
public class UploaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static final int memoryThreshold = 1024*1024*3;
    private static final int maxFileSize = 1024*1024*40;
    private static final int maxRequestSize = 1024*1024*50;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp");
        //checking for multipart request
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
        	request.setAttribute("message","This is not a multipart request.");
        	rd.forward(request, response);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //setting maximum file size to be stored in memory
        //setting temporary location to store files if the file size is more than threshold
        factory.setRepository(new File("D:\\temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        //setting maximum size of file to be uploaded
        //setting maximum size of incoming request (include file + form data)
        String uploadPath = "D:\\uploads";
        System.out.println("uploadPath : "+uploadPath);
        //creating the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
        try {
            //Parsing the request to get the multipart data
            List<FileItem> formData = upload.parseRequest(request);
            if (formData != null && formData.size() > 0) {
                for (FileItem item : formData) {
                    //checking the fields which are not form fields
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File uploadedFile = new File(filePath);
                        //saving the file on disk
                        request.setAttribute("message","File is successfully uploaded at : "+filePath);
        } catch (Exception ex) {
            request.setAttribute("message","Error occurred while uploading file.");
        rd.forward(request, response);


LuanaFAche says:

Very nice post. I really discovered your weblog and wanted to say
that I have got truly enjoyed surfing around your site posts.

After all I am going to be subscribing to the feed and
that i i do hope you write again soon!


Leave a comment


Enter your email address to subscribe to this blog and receive notifications of new posts by email.