Servlet File Upload
Servlet can be used with HTML form tags to allow users to upload files to the server. The uploaded files can be text files, image files, or any document.
The files used in this article are:
upload.jsp: File upload form.
message.jsp: Redirect page after successful upload.
UploadServlet.java: Upload processing Servlet.
Required jar files: commons-fileupload-1.3.2, commons-io-2.5.jar.
The structure diagram is shown below:
>
Note: Servlet 3.0 has built-in file upload features, so developers no longer need to import the Commons FileUpload component into their project.
Next, we will introduce in detail.
Creating a File Upload Form
The following HTML code creates a file upload form. Several points need to be noted:
The form method attribute should be set to POST method, not GET.
The form enctype attribute should be set to multipart/form-data.
The form action attribute should be set to the Servlet file on the backend server that processes the file upload. The example below uses the UploadServlet Servlet to upload files.
To upload a single file, you should use a single <input .../> tag with the attribute type="file". To allow multiple file uploads, include multiple input tags with different name attribute values. The input tags have different name attribute values. The browser will associate a browse button with each input tag.
The upload.jsp file code is as follows:
<%@ 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 Example - tutorialpro.org</title>
</head>
<body>
<h1>File Upload Example - tutorialpro.org</h1>
<form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
Select a file:
<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Writing the Backend Servlet
Below is the source code for UploadServlet, which is used to handle file uploads. Before proceeding, ensure that the dependency packages have been imported into the WEB-INF/lib directory of the project:
The example below relies on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from http://commons.apache.org/proper/commons-fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from http://commons.apache.org/proper/commons-io/.
You can directly download the two dependency packages provided by this site:
The source code for UploadServlet is shown below:
package com.tutorialpro.test;
```java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Upload file storage directory
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
/**
* Upload data and save file
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check if the request contains multipart content
if (!ServletFileUpload.isMultipartContent(request)) {
// If not, stop the process
PrintWriter writer = response.getWriter();
writer.println("Error: The form must include enctype=multipart/form-data");
writer.flush();
return;
}
// Configure upload parameters
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(MEMORY_THRESHOLD);
// Set temporary storage directory
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// Set maximum file upload size
upload.setFileSizeMax(MAX_FILE_SIZE);
// Set maximum request size (includes file and form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// Handle Chinese characters
upload.setHeaderEncoding("UTF-8");
// Create a temporary path to store the uploaded files
// This path is relative to the current application's directory
String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
// Create the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// Parse the request content to extract file data
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// Iterate over form data
for (FileItem item : formItems) {
// Process fields not in the form
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// Print the upload path of the file to the console
System.out.println(filePath);
// Save the file to the disk
item.write(storeFile);
request.setAttribute("message",
"File uploaded successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"Error message: " + ex.getMessage());
}
// Redirect to message.jsp
request.getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
}
message.jsp file code is as follows:
<%@ 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 Result</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>
Compiling and Running the Servlet
Compile the above Servlet UploadServlet and create the required entries in the web.xml file as shown below:
<?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">
<servlet>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.tutorialpro.test.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/TomcatTest/UploadServlet</url-pattern>
</servlet-mapping>
</web-app>
Now try to upload a file using the HTML form you created above. When you visit: http://localhost:8080/TomcatTest/upload.jsp in your browser, the demonstration will look like this: