Home » Java » Enterprise Java » File Upload Example in Servlet and JSP

About Javin Paul

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:


  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.


 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";
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //process only if its multipart content
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);
                for(FileItem item : multiparts){
                        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);
                                 "Sorry this Servlet only handles file upload request");
        request.getRequestDispatcher("/result.jsp").forward(request, response);


 <%@page contentType="text/html" 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 Upload Example in JSP and Servlet - Java web application</title>
            <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" />


 <%@page contentType="text/html" 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 Upload Example in JSP and Servlet - Java web application</title>
        <div id="result">


<?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">




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.


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.



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


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.

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 ....



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

  2. Try placing this code in index.jsp –

    Insert title here

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

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

      input name=”submit” type=”submit” value=”Submit”>

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

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

  5. hi I am getting the following msg

    “Sorry this Servlet only handles file upload request”

    can u please me?

    thanks in Advance

  6. very good tutorial .its working in my project

    Thank you

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

  8. awesome !! works for me :)

  9. 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 :

  10. HTTP Status 404 – /fileuploding/upload

    type Status report

    message /fileuploding/upload

    description The requested resource is not available.

    • Great tutorial.. almost there.. but getting the same error here:

      HTTP Status 404 – /SimpleServlet/upload

      type Status report

      message /SimpleServlet/upload

      description The requested resource is not available.

      Apache Tomcat/7.0.53

  11. I want updating image in server and local database using jsp and servlet

  12. when i m using above code to upload file getting error..

    package does not exist.

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

    pls provide solution.

    • commons-fileupload-1.2.2.jar
      Download above two jars and add them to your project, then build path if working in eclipse else add jars from properties in netbeans

  13. What happens if I have some other fields in my form such as name, address etc..?
    in that case, is there any way to get the photo as request.getParameter(“name”)?

  14. it’s really very nice code.
    Thanx alot..

  15. Sir thanks for this beautiful code.
    It works perfectly.

  16. Sir i am getting error at time of redirecting from index.jsp and error is like as below…

    type Status report

    message /EZaroka/build/upload

    description The requested resource is not available.

    here my programs path is webapps/EZaroka/build/index.jsp
    plz help me.

  17. thanks for the nice article

  18. The code runs and tells me it successfully uploaded the file but where does it upload the file to? I can’t find it anywhere.

  19. can anyone please explain me form tag what is the action referring to? I’m getting http status not found error how should I configure my web.xml? Please let me know as soon as possible thank you.

  20. I tried the above code but it’s not working and I am getting the following error:

    May 05, 2015 11:08:10 AM org.apache.catalina.core.ContainerBase startInternal
    SEVERE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)

    Can anyone please suggest how can I resolve this? I tried without the upload JAVA file tomcat starts perfectly and there is no other instance running when I try this code. Any help will be appreciated.

  21. Can we upload a file chosen from windows machine to a unix server?

  22. John Mickel Almeñe

    works for me . thanks :)

  23. Hey, code works perfectly!

    One question though – how to make the upload process so that the FileUploadHandler renames every file?
    The idea is that the user can upload several files of the same name so that it doesn’t replace the old file with the new (duplicates exist in upload path).

    • You can rename the file after getting the file name based on date and time of upload:

      String name = new File(item.getName()).getName();
      String currentTimestamp = new SimpleDateFormat(“yyyy.MM.dd.HH.mm.ss.ms”).format(new Date());
      String newName = currentTimestamp+name;

      Hope it helps.

Leave a Reply

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


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.