YouTip LogoYouTip

Servlet File Uploading

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 documents. The files used in this tutorial 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. * 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 support for file uploads. Developers no longer need to import the Commons FileUpload component into their project. Next, we will provide a detailed introduction. * * * ## Creating a File Upload Form The following HTML code creates a file upload form. A few points to note: * The form's **method** attribute should be set to **POST**. GET cannot be used. * The form's **enctype** attribute should be set to **multipart/form-data**. * The form's **action** attribute should be set to the Servlet file that will handle the file upload on the backend server. The example below uses the **UploadServlet** Servlet to upload the file. * To upload a single file, you should use a single `` tag with `type="file"`. To allow multiple file uploads, include multiple input tags with different `name` attribute values. The input tags have different values for the `name` attribute. The browser will associate a browse button with each input tag. The code for the upload.jsp file is as follows: File Upload Example -

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: File Upload Result

${message}

Compile the above Servlet UploadServlet and create the required entries in the web.xml file, as shown below: UploadServlet UploadServlet com.tutorial.test.UploadServlet UploadServlet /TomcatTest/UploadServlet Now try uploading a file using the HTML form you created above. When you visit http://localhost:8080/TomcatTest/upload.jsp in your browser, the demo is as follows: !(#)
← Servlet Handling DateServlet Database Access β†’