File Upload Example in Servlet and JSP

Uploading File to server using Servlet and JSP is a common task in Java web application. Before coding your Servlet or JSP to handle file upload request, you need to know little bit about File upload support in HTML and HTTP protocol. If you want your user to choose files from file system and upload to server than you need to use <input type=”file”/>. This will enable to choose any file form file system and upload to server. Next thing is that form method should be HTTP POST with enctype as multipart/form-data, which makes file data available in parts inside request body. Now in order to read those file parts and create a File inside Servlet can be done by using ServletOutputStream. It’s better to use Apache commons FileUpload, an open source library. Apache FileUpload handles all low details of parsing HTTP request which confirm to RFC 1867 or “Form based File upload in HTML”, when you set form method post and content type as “multipart/form-data”.

Important points:

JavaSparrow-med

  1. DiskFileItemFactory is default Factory class for FileItem. When Apache commons read multipart content and generates FileItem, this implementation keep file content either in memory or in disk as temporary file, depending upon threshold size. By default DiskFileItemFactory has threshold size of 10KB and generates temporary files in temp directory, returned by System.getProperty(“java.io.tmpdir”). Both of these values are configurable and it’s best to configure these for production usage. You may get permission issues if user account used for running Server doesn’t have sufficient permission to write files into temp directory.
  2. Choose threshold size carefully based upon memory usage, keeping large content in memory may result in java.lang.OutOfMemory, while having too small values may result in lot’s of temporary files.
  3. Apache commons file upload also provides FileCleaningTracker to delete temporary files created by DiskFileItemFactory. FileCleaningTracker deletes temporary files as soon as corresponding File instance is garbage collected. It accomplish this by a cleaner thread which is created when FileCleaner is loaded. If you use this feature, than remember to terminate this Thread when your web application ends.
  4. Keep configurable details e.g. upload directory, maximum file size, threshold size etc in config files and use reasonable default values in case they are not configured.
  5. It’s good to validate size, type and other details of Files based upon your project requirement e.g. you may wants to allow  upload only images of certain size and certain types e.g. JPEG, PNG etc.

File Upload Example in Java Servlet and JSP

Here is the complete code for uploading files in Java web application using Servlet and JSP. This File Upload Example needs four files :

  1. index.jsp which contains HTML content to setup a form, which allows user to select and upload file to server.
  2. FileUploader Servlet which handles file upload request and uses Apache FileUpload library to parse multipart form data
  3. web.xml to configure servlet and JSP in Java web application.
  4. result.jsp for showing result of file upload operation.

FileUploadHandler.java

 import java.io.File;
import java.io.IOException;
import java.util.List;
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 to handle File upload request from Client
 * @author Javin Paul
 */
public class FileUploadHandler extends HttpServlet {
    private final String UPLOAD_DIRECTORY = "C:/uploads";
  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        //process only if its multipart content
        if(ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);
              
                for(FileItem item : multiparts){
                    if(!item.isFormField()){
                        String name = new File(item.getName()).getName();
                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    }
                }
           
               //File uploaded successfully
               request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex) {
               request.setAttribute("message", "File Upload Failed due to " + ex);
            }          
         
        }else{
            request.setAttribute("message",
                                 "Sorry this Servlet only handles file upload request");
        }
    
        request.getRequestDispatcher("/result.jsp").forward(request, response);
     
    }
  
}

index.jsp

 <%@page contentType="text/html" 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 Upload Example in JSP and Servlet - Java web application</title>
    </head>
 
    <body> 
        <div>
            <h3> Choose File to Upload in Server </h3>
            <form action="upload" method="post" enctype="multipart/form-data">
                <input type="file" name="file" />
                <input type="submit" value="upload" />
            </form>          
        </div>
      
    </body>
</html>

result.jsp

 <%@page contentType="text/html" 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 Upload Example in JSP and Servlet - Java web application</title>
    </head>
 
    <body> 
        <div id="result">
            <h3>${requestScope["message"]}</h3>
        </div>
      
    </body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

   <servlet>
        <servlet-name>FileUploadHandler</servlet-name>
        <servlet-class>FileUploadHandler</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadHandler</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
  
  
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

In summary just keep three things in mind while uploading files using Java web application

  1. Use HTML form input type as File to browse files to upload
  2. Use form method as post and enctype as multipart/form-data
  3. Use Apache commons FileUpload in Servlet to handle HTTP request with multipart data.

Dependency

In order to compile and run this Java web application in any web server e.g. Tomcat, you need to include following dependency JAR in WEB-INF lib folder.

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

If you are using Maven than you can also use following dependencies :

 <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.2.2</version>
</dependency>
<dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.4</version>
</dependency>

That’s all on How to upload Files using Servlet and JSP in Java web application. This File Upload example can be written using JSP, Filter or Servlet because all three are request’s entry point in Java web application. I have used Servlet for handling File upload request for simplicity. By the way from Servlet 3.0 API, Servlet is supporting multipart form data and you can use getPart() method of HttpServletRequest to handle file upload.
 

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

13 Responses to "File Upload Example in Servlet and JSP"

  1. Doe says:

    Your index.jsp and result.jsp are identical (it is the result.jsp)

  2. Priya says:

    Try placing this code in index.jsp -

    Insert title here

    • Priya says:

      Sorry the HTML didnt appeared in the comment, so i m removing opening lt
      head>
      meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
      title>Insert title here
      /head>

      body>
      form action=”upload” method=”post” name=”uploadForm” enctype=”multipart/form-data”>
      p>
      input name=”uploadfile” type=”file” size=”50″>
      /p>

      input name=”submit” type=”submit” value=”Submit”>
      /form>
      /body>
      /html>

  3. Richard says:

    Excelente he utilizado tu codigo y me ha funcionado..Gracias por tu gran ayuda

  4. Richard says:

    Excellent I have used your code and it works .. Thanks for your great help

  5. jaiswal says:

    hi I am getting the following msg

    “Sorry this Servlet only handles file upload request”

    can u please me?

    thanks in Advance

  6. jaiswal says:

    very good tutorial .its working in my project

    Thank you

  7. Rakesh says:

    but How to change upload directory path………………….c:\upload is not supported

  8. Dass says:

    Good………..

  9. John Mickel says:

    awesome !! works for me :)

  10. Namita says:

    Hi,
    I wants to get other two parameter values along with file type value, but when i use code as below it shows null values for other parameters. Plz help…

    Enter Name:
    Enter Password :
    Select Image :

  11. sachin says:

    HTTP Status 404 – /fileuploding/upload

    type Status report

    message /fileuploding/upload

    description The requested resource is not available.

Leave a Reply


three + = 10



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books