File Upload Example -
Select a file:Below is the source code for UploadServlet, used to handle the file upload. Before proceeding, we must ensure the dependency packages have been added to the project's WEB-INF/lib directory: * The following example depends on FileUpload, so you must ensure the latest version of **commons-fileupload.x.x.jar** is in your classpath. It can be downloaded from [http://commons.apache.org/proper/commons-fileupload/](http://commons.apache.org/proper/commons-fileupload/). * FileUpload depends on Commons IO, so you must ensure the latest version of **commons-io-x.x.jar** is in your classpath. It can be downloaded from [http://commons.apache.org/proper/commons-io/](http://commons.apache.org/proper/commons-io/). You can directly download the two dependency packages provided by this site: * [commons-fileupload-1.3.2.jar](http://static.example.com/download/commons-fileupload-1.3.2.jar) * [commons-io-2.5.jar](http://static.example.com/download/commons-io-2.5.jar) The source code for UploadServlet is as follows: package com.tutorial.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 */@WebServlet("/UploadServlet")public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; // Directory to store uploaded files 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 the request contains multipart contentif (!ServletFileUpload.isMultipartContent(request)) { // If not, stop PrintWriter writer = response.getWriter(); writer.println("Error: The form must contain enctype=multipart/form-data"); writer.flush(); return;} // Configure upload parameters DiskFileItemFactory factory = new DiskFileItemFactory(); // Set memory threshold - beyond this, temporary files will be created and stored in the temp 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); // Handle Chinese characters upload.setHeaderEncoding("UTF-8"); // Construct temporary path to store uploaded files // This path is relative to the current application's directory String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY; // Create directory if it doesn't exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // Parse request content to extract file data @SuppressWarnings("unchecked") List 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 file upload path to the console System.out.println(filePath); // Save file to disk item.write(storeFile); request.setAttribute("message", "File uploaded successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "Error message: " + ex.getMessage()); } // Forward to message.jsp request.getServletContext().getRequestDispatcher("/message.jsp").forward( request, response); }} The code for the message.jsp file is as follows:
YouTip