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:
1)commons-fileupload-x.x.x.jar
2)commons-io-x.x.x.jar

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

Files:
1)home.jsp:
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"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>File Uploader Example</title>
  </head>
   <body>
     <center>
	<form method="post" action="uploadServlet" enctype="multipart/form-data">
	Select file to upload:
	<input type="file" name="uploadFile" />
	<br/><br/>
	<input type="submit" value="Upload" />
	</form>
	<h5>${message}</h5>
	</center>
  </body>
</html>

2)web.xml:
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="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<servlet>
		<servlet-name>uploader</servlet-name>
		<servlet-class>com.fileuploader.servlet.UploaderServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>uploader</servlet-name>
		<url-pattern>/uploadServlet</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>home.jsp</welcome-file>
	</welcome-file-list>
</web-app>

3)UploaderServlet.java:
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.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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
        factory.setSizeThreshold(memoryThreshold);
        //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
        upload.setFileSizeMax(maxFileSize);
         
        //setting maximum size of incoming request (include file + form data)
        upload.setSizeMax(maxRequestSize);
 
        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()) {
            uploadDir.mkdir();
        }
 
        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
                        item.write(uploadedFile);
                        request.setAttribute("message","File is successfully uploaded at : "+filePath);
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message","Error occurred while uploading file.");
        }
        rd.forward(request, response);
    }
}

COMMENTS ( 4 )

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!

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

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

Categories