JSP File Uploading
JSP can be used together with the HTML form tag to allow users to upload files to the server. The uploaded file can be a text file, an image file, or any document.
In this chapter we use a Servlet to handle file uploads. The files used are:
- upload.jsp: the file upload form.
- message.jsp: the page to redirect to after a successful upload.
- UploadServlet.java: the Servlet that handles the upload.
- JAR files that need to be imported: commons-fileupload-1.3.2, commons-io-2.5.jar.
The structure diagram is shown below:

Next we will introduce it in detail.
Create an Upload Form
The following HTML code creates a file upload form. The following points should be noted:
- The form method attribute should be set to POST method; the GET method cannot be used.
- The form enctype attribute should be set to multipart/form-data.
- The form action attribute should be set to the Servlet file on the back-end server that handles the file upload. The following example 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 files to be uploaded, include multiple input tags with different name attribute values. The input tags have different name attribute values. The browser associates a browse button with each input tag.
The code of the upload.jsp file is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
文件上传实例 - Runoob Tutorial
文件上传实例 - Runoob Tutorial
Writing the Back-End Servlet
The following is the source code of UploadServlet for handling file uploads. Before this, we first make sure the dependency packages have been imported into the project's WEB-INF/lib directory:
- The following example depends on FileUpload, so be sure to have the latest version of commons-fileupload.x.x.jar in your classpath. You can download it from http://commons.apache.org/proper/commons-fileupload/ for download.
- FileUpload depends on Commons IO, so be sure to have the latest version of commons-io-x.x.jar in your classpath. You can download it from http://commons.apache.org/proper/commons-io/ for download.
You can directly download the two dependency packages provided by this site:
The source code of UploadServlet is as follows:
package com.runoob.test;
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
*/
// If web.xml is not configured, you can use the following code
// @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 configuration
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 it is a multimedia upload
if (!ServletFileUpload.isMultipartContent(request)) {
// If not, stop
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
// Configure upload parameters
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set memory threshold - if exceeded, a temporary file will be generated and stored in the temporary directory
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 value
upload.setFileSizeMax(MAX_FILE_SIZE);
// Set maximum request value (including file and form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// Chinese processing
upload.setHeaderEncoding("UTF-8");
// Construct a temporary path to store uploaded files
// This path is relative to the current application directory
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
// Create 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 formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// Represents single data record
for (FileItem item : formItems) {
// Handle 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);
// Output the file upload path to the console
System.out.println(filePath);
// Save file to disk
item.write(storeFile);
request.setAttribute("message",
"文件上传成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"错误信息: " + ex.getMessage());
}
// Jump to message.jsp
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
}
The code of the message.jsp file is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
文件上传结果
${message}
Compiling and Running the Servlet
Compile the Servlet UploadServlet above and create the required entries in the web.xml file, as shown below:
UploadServlet
UploadServlet
com.runoob.test.UploadServlet
UploadServlet
/TomcatTest/UploadServlet
Now try using the HTML form you created above to upload a file. When you visit http://localhost:8080/TomcatTest/upload.jsp in the browser, the demonstration is as follows:
