Você está na página 1de 5

Java Servlet file upload example

This Servlet File Upload tutorial explains how to handle the file upload in Servlets.

This tutorial explains

1. Handling file upload using apache commons-file file upload API.

File upload specification is contained in RFC 1867 ‘form based file upload in HTML’.

Handling file upload using commons file upload API

The commons File Upload package makes it easy to add robust, high performance, file
upload capacity to your Servlets and web applications.

Download and install Commons File Upload package

First of all, download the latest version of commons file upload package from here.
FileUpload depends on Commons IO package, so download the version mentioned on the
FileUpload dependency page. t the time of writing this tutorial, the latest version of
Commons File Upload is 1.2.1 which depends on Commons IO version 1.3.2. Installation
is very easy. Extract both of the downloaded zip files and put commons-fileupload-
1.2.1.jar and commons-io-1.3.2.jar jar files into the WEB-INF/lib folded of your web

The next step is to create the HTML file.

Create the HTML file with file input field

It is very easy to write the HTML file that supports file upload.

1. Set the content type of the HTML form to multipart/form-data.

2. Add the file input type filed into the HTML form.

As specified in RFC1867, to support the file upload, Content type of the POST request
must be set to multipart/form-data. This can be done by setting the value of ENCTYPE
attribute of HTML form to multipart/form-data

<form action=”/FileUploadServlet” ENCTYPE=”mulipart/form-data” method=”POST”>

File input type field displays a file input box which allows user to select a file to upload.
<input type=”file” name=”file”/>

There can be any number of file input fields in a HTML form.

Copy the following code into upload.html file. Save the file directly under the web
application root directory

<p>Commons File Upload Example</p>
<form action="Commonsfileuploadservlet"
enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>

The File Upload Servlet

Copy the following code into CommonsFileUploadServlet.java.

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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

public class CommonsFileUploadServlet extends HttpServlet {

private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;

public void init(ServletConfig config) throws ServletException {

tmpDir = new File(TMP_DIR_PATH);
if(!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is
not a directory");
String realPath =
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+"
is not a directory");

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<h1>Servlet File Upload Example using Commons
File Upload</h1>");

DiskFileItemFactory fileItemFactory = new

DiskFileItemFactory ();
*Set the size threshold, above which content will be
stored on disk.
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
* Set the temporary directory to store the uploaded
files of size above threshold.

ServletFileUpload uploadHandler = new

try {
* Parse the request
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
* Handle Form Fields.
if(item.isFormField()) {
out.println("File Name =
"+item.getFieldName()+", Value = "+item.getString());
} else {
//Handle Uploaded files.
out.println("Field Name = "+item.getFieldName()+", File Name =
", Content type =
", File Size =
* Write file to the ultimate
File file = new
}catch(FileUploadException ex) {
log("Error encountered while parsing the
} catch(Exception ex) {
log("Error encountered while uploading file",ex);

Compile the CommnonsFileUploadServlet.java file as explained in tutorial Servlet

Example and put the class file inside WEB-INF/classes directory.

Web.xml servlet mapping


Create two folders tmp and files under your web application root directory. deploy the
application to tomcat server and start the server.
Access the application in browser and upload any file. The file would be uploaded to
server and saved under the files directory of the application.