You are on page 1of 8

8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial

Javarevisited
Blog about Java programming language, FIX Protocol, Tibco RV

Home core java spring hibernate collections multithreading design patterns interview questions coding data structure OOP java 8 books About Me

File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload -
Tutorial
Uploading File to the 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 a little bit

about File upload support in HTML and HTTP protocol. If you

want your user to choose files from the file system and upload to
the server then you need to use <input type="file"/>. This

will enable to choose any file from the file system and upload

to a 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 conform to RFC

1867 or "Form-based File upload in HTML when you set form method post and content type as "multipart/form-data".

Apache Commons FileUpload - Important points:


1) DiskFileItemFactory is default Factory class for FileItem. When Apache commons read multipart content and

generate FileItem, this implementation keeps file content either in memory or in the disk as a 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 the temp directory.

Interview Questions

core java interview question (170)


data structure and algorithm (55)
interview questions (54)
Coding Interview Question (38)
SQL Interview Questions (28)
design patterns (27)
2) Choose threshold size carefully based upon memory usage, keeping large content in memory may result in
object oriented programming (25)
java.lang.OutOfMemory, while having too small values may result in lot's of temporary files.
thread interview questions (22)
collections interview questions (18)
3) Apache commons file upload also provides FileCleaningTracker for deleting temporary files created by
database interview questions (18)
DiskFileItemFactory. FileCleaningTracker deletes temporary files as soon as corresponding File instance is garbage
servlet interview questions (17)
collected. It accomplishes this by a cleaner thread which is created when FileCleaner is loaded. If you use this feature, then
spring interview questions (12)
remember to terminate this Thread when your web application ends.
Programming interview question (7)
hibernate interview questions (6)
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.

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 1/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial
5) It's good to validate size, type and other details of Files based upon your project requirement e.g. you may want to allow
Mit welcher Marke(n) sind Sie
upload only images of a certain size and certain types e.g. JPEG, PNG etc. vertraut?

G Skill
This site uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information LEARN MORE GOT IT
about your use of this site is shared with Google. By using this site, you agree to its use of cookies. Corsair
File Upload Example in Java Servlet and JSP Crucial
Kingston
Here is the complete code for uploading files in Java web application using Servlet and JSP. This File Upload Example needs
Oder
four files :

1. index.jsp which contains HTML content to set up a form, which allows the user to select and upload a file to the server.
Vote
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 the result of file upload operation.

Recommended Reading
FileUploadHandler.java
5 Books to Learn Core Java in 2017
import java.io.File;
5 Books to Learn Java 8 and Functional
import java.io.IOException; Programming
import java.util.List;
5 Books to Learn Spring MVC in 2017
import javax.servlet.ServletException;
3 Books to Learn Hibernate in 2017
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; Top 5 JavaScript Books for Web Developers
import javax.servlet.http.HttpServletResponse; Best book to Learn Servlet and JSP
import org.apache.commons.fileupload.FileItem; 5 Books to Learn REST and RESTFul Web Services
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
5 Books to improve Coding Skills
import org.apache.commons.fileupload.servlet.ServletFileUpload;
5 Advanced SQL Books

/**
* 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 {
Search This Blog
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request); Search

Translate this blog


for(FileItem item : multiparts){
if(!item.isFormField()){ Select Language
String name = new File(item.getName()).getName();
Powered by Translate
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);

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 2/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial

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>
Java Tutorials
</html>
date and time tutorial (21)
FIX protocol tutorial (16)
result.jsp
java collection tutorial (61)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
java IO tutorial (25)

"http://www.w3.org/TR/html4/loose.dtd"> Java JSON tutorial (8)


<html> Java multithreading Tutorials (37)
<head> Java Programming Tutorials (27)
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Java xml tutorial (11)
<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>

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 3/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial
<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 then you can also use following dependencies :

<dependency> Subscribe to Download the E-book


<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 requests 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 Download Buildinga REST API with
The E-book Spring 4?
can use getPart() method of HttpServletRequest to handle file upload.

Email address... Submit

Followers
Followers (4315) Next

Dwarf Cherry Tree (Prunus 20 orange seeds dwarf A Kids Book 10 Seeds Dwarf Peach Fruit
avium) Self-Fertile Frui Bonsai Mandarin Orange About...Avocados! Fun Tree Indoor/Outdoor
Seeds Edible Fruit tree for Facts, Photos, and Recipes
$5.99 home garden (for 6-12 years old) (Plant $1.40 Follow
(2) $10.99 $0.99 (59)
Blog Archive
Ads by Amazon
2017 ( 135 )
2016 ( 166 )
2015 ( 126 )
You May Like Sponsored Links by Taboola
2014 ( 100 )
If you own a computer you must try this game... 2013 ( 127 )
Vikings: Free Online Game December ( 5 )
November ( 7 )
October ( 3 )

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 4/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial
The Most Addictive Game Of The Year! September ( 3 )
Elvenar - Free Online Game August ( 13 )
July ( 12 )
JQuery Selectors Examples to find elements in
25 Richest Kids of 2017 DOM ...
TwinkleMag 2 Books to Prepare Oracle Java Certification
Exams...
How to bypass Websense Internet Filter at
Office, ...
25 Most Beautiful Muslim Actresses
File Upload Example in Java using Servlet, JSP
TopViralHot
and...
How to create Thread Pools using Java 1.5
Executor...
Finally You Can Track Your Car Using Your Smartphone How to Configure HTTPS (SSL) in Tomcat 6 and 7
TRACKR BRAVO
Jav...
10 Things Every Java Programmer Should Know
about ...
Difference between linked list and array data
15 Most Beautiful Women In The World stru...
Crazy Freelancer When to make a method static in Java
Top 5 JQuery books for Beginners and Web
developer...

End Your Nightly Snoring Nightmare With This Simple Solution How SSL, HTTPS and Certificates works in Java
web ...
My Snoring Solution
Role based Access control using Spring Security
an...

June ( 7 )
5 Foods You Wouldn't Think Are Good for You
May ( 10 )
BleuBloom.com
April ( 18 )
March ( 15 )
February ( 18 )
January ( 16 )
You might like:
10 Java Exception and Error Interview Questions Answers 2012 ( 214 )
3 ways to solve java.lang.NoClassDefFoundError in Java J2EE 2011 ( 135 )
5 Difference between Constructor and Static Factory method in Java- Pros and Cons
2010 ( 30 )
How Maven find dependency JARs while building Java Project

Recommended by

Posted by Javin Paul Pages

Labels: core java , jsp-servlet , programming Privacy Policy


Location: United States
Copyright by Javin Paul 2010-2017. Powered by
Blogger.
19 comments :
Anonymous said...
Can I upload an image by using this way? Thanks!

March 20, 2014 at 9:09 AM

Anonymous said...
upon execution of the above code i am encountering a 404 error after clicking on upload. what to do?

March 27, 2014 at 12:26 AM

Anonymous said...
Hi... its functioning well but there is a problem in that images also gets saved in classes folder with other class files...
it makes the war file toooo heavy to deploy

March 31, 2014 at 4:27 AM

syed rizwan said...


Try this :

Before coding download the package : cos.jar

First create a HTML file and upload.jsp

upload.jsp : Add the given below:

import="com.oreilly.servlet.MultipartRequest"

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 5/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial
MultipartRequest m = new MultipartRequest(request,"e:/syed",10590378);

out.println("Uploaded");

April 16, 2014 at 3:46 AM

saddam mehri said...


stp , c'est que cette erreur :
File Upload Failed due to java.lang.ClassCastException:
org.netbeans.modules.web.monitor.server.MonitorRequestWrapper cannot be cast to
org.apache.tomcat.util.http.fileupload.RequestContext

le code est:
List multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);

mais il affiche une erreur et m'a obliger a corriger l'erreur comme ca :


List multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest((RequestContext) request);

May 20, 2014 at 12:25 PM

Anonymous said...
Hello ! :)
I'm trying to get this upload thing to work for 3 hours now, i'm getting crazy !
Your example seemed very good so I copied it aaaaaand it doesn't work :(
I'm getting the message "File Uploaded Successfully" but there's no file where it should...
I've found out that the issue is with the line :

List multiparts = new ServletFileUpload( new DiskFileItemFactory()).parseRequest(request);

My list is empty...

I hope that you, or someone else, can help me !

Thanks :)
William

August 6, 2014 at 2:57 AM

Anonymous said...
Nevermind, I've found the solution !
For those it might concern :
The problem was with the line
"< input type="file" name="file" />"
I didn't have the "name" field, but an "id" field instead. Silly !

So, thank you very much for your working example ! ;)


William

August 6, 2014 at 3:14 AM

Nitish Agarwal said...


Hi, i used above mentioned code to upload a file and also placed jar file at corresponding path. but i am 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 assist to resolve it.

September 8, 2014 at 5:54 AM

Anonymous said...
how to get the attachment if it located at other server. it is only can retrieve from same server only ?

September 10, 2014 at 6:28 PM

+plain-jane said...
any ideas how to do it if my destination location is sftp server? thanks~

December 8, 2014 at 12:06 AM

Anonymous said...

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 6/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial
Type Safety Error: List needs Unchecked Conversion to confirm List
Please help me to solve this error

February 8, 2015 at 1:12 AM

Nitish Chitranshi said...


I have used the above code. It is working fine if I run it on the Server installed on windows platform, but while
executing this on the Unix server, the image is not getting uploaded. Can you please tell me how to upload the image
in the unix server?

September 26, 2015 at 5:20 AM

Javin Paul said...


@Nitish, this is Java code and it's using Java library, so its supposed to work on both Windows and Linux. Can you
please tell us more about the issue? are you getting any exception on Linux? What exactly means you are not able to
upload images?

September 26, 2015 at 6:05 AM

Irshad Qureshi said...


Hi, i used above mentioned code to upload a file and also placed jar file at corresponding path. but i am getting error..

error is :
http 505 sevlet class not found

November 12, 2015 at 9:36 PM

Unknown said...
Great work...

April 29, 2016 at 3:45 PM

Sathish Sundaram said...


i want make name for uploading file.pls help me.

June 2, 2016 at 10:48 PM

Anonymous said...
request.getRequestDispatcher("/result.jsp").include(request, response); does not redirect to the jsp page.

What should I do if I want this to be redirected to another page?

September 29, 2016 at 7:41 AM

Vaibhav Shrivastav said...


Hi , When i get file in spring rest API using Multi-part. I am not storing file on tomcat server . But why is store in my
tomcat server root directory by default. Please give me solutions and do want to store file on server. Please help me

June 20, 2017 at 2:51 AM

Javin Paul said...


Hello @Vaibhav, Your server must be using default location for storing uploaded file. If you want to store file
somewhere else, just look for that option in Tomcat. Where exactly you want to store your files?

June 20, 2017 at 6:33 AM

Post a Comment

Enter your comment...

Comment as: Select profile...

Publish Preview

Newer Post Home Older Post

Subscribe to: Post Comments ( Atom )

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 7/8
8/31/2017 File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial

http://javarevisited.blogspot.co.uk/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html 8/8

You might also like