YouTip LogoYouTip

Jsp File Uploading

JSP 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. 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 for handling the upload. * Required JAR files: commons-fileupload-1.3.2, commons-io-2.5.jar. The structure diagram is as follows: !(#) Next, we will explain in detail. * * * ## Creating a File Upload Form The following HTML code creates a file upload form. Note the following points: * 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 point to the Servlet on the backend server that will process the file upload. The example below uses the **UploadServlet** Servlet to upload the file. * To upload a single file, you should use a single `` tag with the attribute `type="file"`. To allow multiple file uploads, include multiple input tags with different values for the `name` attribute. The input tags have different `name` attribute values. 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, which is used to handle file uploads. Before proceeding, 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 on this site: * [commons-fileupload-1.3.2.jar] * [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 */// 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; // 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 is a multipart upload if (!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 = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY; // Create the 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); // Output the file upload path to the console System.out.println(filePath); // Save the file to disk item.write(storeFile); request.setAttribute("message", "File uploaded successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "Error message: " + ex.getMessage()); } // Redirect to message.jsp 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 necessary entries in the `web.xml` file, as shown below: UploadServlet UploadServlet com.tutorial.test.UploadServlet UploadServlet /TomcatTest/UploadServlet 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 is as follows: !(#)
← Jsp Handling DateJsp Session β†’