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

- 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.
- 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.
- 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.
- 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.
- 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 :- index.jsp which contains HTML content to setup a form, which allows user to select and upload file to server.
- FileUploader Servlet which handles file upload request and uses Apache FileUpload library to parse multipart form data
- web.xml to configure servlet and JSP in Java web application.
- result.jsp for showing result of file upload operation.
FileUploadHandler.java
| 01 | importjava.io.File; | 
| 02 | importjava.io.IOException; | 
| 03 | importjava.util.List; | 
| 04 | importjavax.servlet.ServletException; | 
| 05 | importjavax.servlet.http.HttpServlet; | 
| 06 | importjavax.servlet.http.HttpServletRequest; | 
| 07 | importjavax.servlet.http.HttpServletResponse; | 
| 08 | importorg.apache.commons.fileupload.FileItem; | 
| 09 | importorg.apache.commons.fileupload.disk.DiskFileItemFactory; | 
| 10 | importorg.apache.commons.fileupload.servlet.ServletFileUpload; | 
| 11 | 
| 12 | /** | 
| 13 |  * Servlet to handle File upload request from Client | 
| 14 |  * @author Javin Paul | 
| 15 |  */ | 
| 16 | publicclassFileUploadHandler extendsHttpServlet { | 
| 17 |     privatefinalString UPLOAD_DIRECTORY = "C:/uploads"; | 
| 18 |    | 
| 19 |     @Override | 
| 20 |     protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) | 
| 21 |             throwsServletException, IOException { | 
| 22 |        | 
| 23 |         //process only if its multipart content | 
| 24 |         if(ServletFileUpload.isMultipartContent(request)){ | 
| 25 |             try{ | 
| 26 |                 List<FileItem> multiparts = newServletFileUpload( | 
| 27 |                                          newDiskFileItemFactory()).parseRequest(request); | 
| 28 |                | 
| 29 |                 for(FileItem item : multiparts){ | 
| 30 |                     if(!item.isFormField()){ | 
| 31 |                         String name = newFile(item.getName()).getName(); | 
| 32 |                         item.write( newFile(UPLOAD_DIRECTORY + File.separator + name)); | 
| 33 |                     } | 
| 34 |                 } | 
| 35 |             | 
| 36 |                //File uploaded successfully | 
| 37 |                request.setAttribute("message", "File Uploaded Successfully"); | 
| 38 |             } catch(Exception ex) { | 
| 39 |                request.setAttribute("message", "File Upload Failed due to "+ ex); | 
| 40 |             }           | 
| 41 |           | 
| 42 |         }else{ | 
| 43 |             request.setAttribute("message", | 
| 44 |                                  "Sorry this Servlet only handles file upload request"); | 
| 45 |         } | 
| 46 |      | 
| 47 |         request.getRequestDispatcher("/result.jsp").forward(request, response); | 
| 48 |       | 
| 49 |     } | 
| 50 |    | 
| 51 | } | 
index.jsp
| 01 | <%@page contentType="text/html" pageEncoding="UTF-8"%> | 
| 02 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" | 
| 04 | <html> | 
| 05 |     <head> | 
| 06 |         <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"> | 
| 07 |         <title>File Upload Example in JSP and Servlet - Java web application</title> | 
| 08 |     </head> | 
| 09 |   | 
| 10 |     <body>  | 
| 11 |         <divid="result"> | 
| 12 |             <h3>${requestScope["message"]}</h3> | 
| 13 |         </div> | 
| 14 |        | 
| 15 |     </body> | 
| 16 | </html> | 
result.jsp
| 01 | <%@page contentType="text/html" pageEncoding="UTF-8"%> | 
| 02 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" | 
| 04 | <html> | 
| 05 |     <head> | 
| 06 |         <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"> | 
| 07 |         <title>File Upload Example in JSP and Servlet - Java web application</title> | 
| 08 |     </head> | 
| 09 |   | 
| 10 |     <body>  | 
| 11 |         <divid="result"> | 
| 12 |             <h3>${requestScope["message"]}</h3> | 
| 13 |         </div> | 
| 14 |        | 
| 15 |     </body> | 
| 16 | </html> | 
web.xml
| 01 | <?xmlversion="1.0"encoding="UTF-8"?> | 
| 02 | <web-appversion="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"> | 
| 03 | 
| 04 |    <servlet> | 
| 05 |         <servlet-name>FileUploadHandler</servlet-name> | 
| 06 |         <servlet-class>FileUploadHandler</servlet-class> | 
| 07 |     </servlet> | 
| 08 |     <servlet-mapping> | 
| 09 |         <servlet-name>FileUploadHandler</servlet-name> | 
| 10 |         <url-pattern>/upload</url-pattern> | 
| 11 |     </servlet-mapping> | 
| 12 |    | 
| 13 |    | 
| 14 |     <session-config> | 
| 15 |         <session-timeout> | 
| 16 |             30 | 
| 17 |         </session-timeout> | 
| 18 |     </session-config> | 
| 19 | 
| 20 |     <welcome-file-list> | 
| 21 |         <welcome-file>index.jsp</welcome-file> | 
| 22 |     </welcome-file-list> | 
| 23 | 
| 24 | </web-app> | 
- Use HTML form input type as File to browse files to upload
- Use form method as post and enctype as multipart/form-data
- 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 than you can also use following dependencies :
| 01 | <dependency> | 
| 02 |      <groupId>commons-fileupload</groupId> | 
| 03 |      <artifactId>commons-fileupload</artifactId> | 
| 04 |      <version>1.2.2</version> | 
| 05 | </dependency> | 
| 06 | <dependency> | 
| 07 |      <groupId>commons-io</groupId> | 
| 08 |      <artifactId>commons-io</artifactId> | 
| 09 |      <version>2.4</version> | 
| 10 | </dependency> | 
No comments:
Post a Comment