This tutorial explains
File upload specification is contained in RFC 1867 ‘form based file upload in HTML’.
Note: Servlet 3.0 Specification has built in file upload support. With servlet 3.0, you don't need to use any external library like commons file upload. Read this @MultipartConfig : Servlet 3.0 File Upload Example For more details on built in file upload support in servlet 3.0 specification.
The commons File Upload package makes it easy to add robust, high performance, file upload capacity to your Servlets and web applications.
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.
The next step is to create the HTML file.
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
<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
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <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="text" name="param" value="中文" /><br> <input type="Submit" value="Upload File"><br> </form> </body> </html>
Copy the following code into CommonsFileUploadServlet.java.
package com.test.day15.fileupload; import java.io.File; /** * Servlet implementation class CommonsFileUploadServlet */ public class CommonsFileUploadServlet extends HttpServlet { /** * */ private static final long serialVersionUID = -5456408232882331065L; private static final String TMP_DIR_PATH = "c:\\tmp"; private File tmpDir; private static final String DESTINATION_DIR_PATH = "E:/Test File/2012-2-4"; private File destinationDir; /** * @see HttpServlet#HttpServlet() */ public CommonsFileUploadServlet() { super(); // TODO Auto-generated constructor stub } public void init(ServletConfig config) throws ServletException { super.init(config); tmpDir = new File(TMP_DIR_PATH); if (!tmpDir.exists()) { tmpDir.mkdirs(); } if (!tmpDir.isDirectory()) { throw new ServletException(TMP_DIR_PATH + " is not a directory"); } destinationDir = new File(DESTINATION_DIR_PATH); if (!destinationDir.exists()) { destinationDir.mkdirs(); } if (!destinationDir.isDirectory()) { throw new ServletException(DESTINATION_DIR_PATH + " is not a directory"); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>"); out.println(); 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. */ fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); 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()) { System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString("UTF-8")); out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString("UTF-8")); } else { // Handle Uploaded files. out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); /* * Write file to the ultimate location. */ File file = new File(destinationDir, item.getName()); item.write(file); } out.close(); } } catch (FileUploadException ex) { log("Error encountered while parsing the request", ex); } 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.
<servlet> <servlet-name>CommonsFileUploadServlet</servlet-name> <servlet-class>CommonsFileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CommonsFileUploadServlet</servlet-name> <url-pattern>/Commonsfileuploadservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/upload.html</welcome-file> </welcome-file-list>Create two folders tmp and files under your web application root directory. deploy the application to tomcat server and start the server.