Java Servlet File Upload Example
Java Servlet File Upload Example
This Servlet File Upload tutorial explains how to handle the file upload in Servlets.
File upload specification is contained in RFC 1867 ‘form based file upload in HTML’.
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
application.
It is very easy to write the HTML file that supports file upload.
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
File input type field displays a file input box which allows user to select a file to upload.
<input type=”file” name=”file”/>
<html>
<head></head>
<body>
<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>
</form>
</body>
</html>
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;
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.