Java File Upload Example with Servlet, JSP and Apache Commons FileUpload
- Details
- Written by Nam Ha Minh
- Last Updated on 25 June 2019   |   Print Email
This article provides code example of a sample Java web application that demonstrates how to implement file upload functionality based on Apache Common FileUpload API, servlet and JSP.
The application consists of the following source files:
- upload.jsp: A JSP page that displays an upload form.
- UploadServlet.java: A Java servlet that handles file upload.
- message.jsp: A JSP page that displays message to user after the file is uploaded.
- web.xml: defines and configures URL mapping for the servlet.
Java runtime configuration:
- Servlet 2.5+
- JRE 1.5+
Eclipse project structure:
1. Code Upload form (upload.jsp)
<%@ 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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>File Upload Demo</title> </head> <body> <center> <form method="post" action="uploadFile" enctype="multipart/form-data"> Select file to upload: <input type="file" name="uploadFile" /> <br/><br/> <input type="submit" value="Upload" /> </form> </center> </body> </html>
2. Code File Upload Servlet class (FileUploadServlet.java)
package net.codejava.upload; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * A Java servlet that handles file upload from client. * * @author www.codejava.net */ public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; // location to store file uploaded private static final String UPLOAD_DIRECTORY = "upload"; // upload settings private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB /** * Upon receiving file upload submission, parses the request to read * upload data and saves the file on disk. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("message", "Upload has been done successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // redirects client to message page getServletContext().getRequestDispatcher("/message.jsp").forward( request, response); } }
3. Code Message page (message.jsp)
<%@ 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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Upload Result</title> </head> <body> <center> <h2>${message}</h2> </center> </body> </html>
4. Configure Web deployment descriptor file (web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>FileUploadServletExample</display-name> <servlet> <display-name>FileUploadServlet</display-name> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>net.codejava.upload.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/uploadFile</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> </web-app>
5. Required libraries
Download distribution and extract zip archive, then pick up jar file of the following libraries:
- Apache Commons FileUpload: commons-fileupload-1.2.2.jar
- Apache Commons IO: commons-io-2.2.jar
6. Testing the application
URL:http://localhost:8080/FileUploadServletExample
Pick a file to upload:
Result:
NOTES:
As shown in the above code example, the sample application stores uploaded file in a directory named “upload”, which is relative to the web application’s directory and will be created if not exist. However, saving files into a location relative to the application’s directory is not recommended, because the directory can be deleted when the application is redeployed, making the previous uploaded files lost. So it’s recommended to store your files in another location which is independent of the application’s directory.
Related File Upload Tutorials:
- Java File Upload Example with Servlet 3.0 API
- Spring MVC File Upload Tutorial with Eclipse IDE
- Upload file with Struts
- Upload files to database (Servlet + JSP + MySQL)
- Upload Files to Database with Spring MVC and Hibernate
Other Java Servlet Tutorials:
- Java Servlet Quick Start for beginners (XML)
- Java Servlet for beginners (annotations)
- Handling HTML form data with Java Servlet
- Java File Download Servlet Example
Comments
Kindly check my video tutorial here: www.youtube.com/watch?v=ryRQ6qXLLYM
like MVC project
Kindly refer to the following tutorials:
- Java Servlet Download File Example: codejava.net/.../...
- How to display images from database in JSP page with Java Servlet: codejava.net/.../...
I am new to Java Proramming.
Can we use servlet to read the data from uploaded file and then display in a webpage??
If yes, what is the structure of files. Please explain in brief...