English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSP File Upload

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 document.

In this chapter, we use Servlet to handle file uploads, and the files used are:

  • upload.jsp : File upload form.

  • message.jsp : The page to jump to after upload is successful.

  • UploadServlet.java : Servlet for upload processing.

  • The required jar files: commons-fileupload-1.3.2、commons-io-2.5.jar.

The structure diagram is as shown below:


Next, we will introduce in detail.

Create a file upload form

The following HTML code creates a file upload form. The following points need to be noted:

  • form method The attribute should be set to POST Method, cannot use GET method.

  • form enctype The attribute should be set to multipart/form-data.

  • form action The attribute should be set to the Servlet file that handles file uploads on the backend server. The following example uses UploadServlet Servlet to upload the file.

  • To upload a single file, you should use a single <input .../> The <input> tag. To allow multiple file uploads, include multiple input tags with different name attribute values. Input tags have different values for the name attribute. The browser will associate a browse button with each input tag.

>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 - Basic Tutorial Website</title>
</head>
<body>
<h1>File Upload Example - Basic Tutorial Website</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>

Write background Servlet

The following is the source code of UploadServlet, which is used to handle file uploads. Before that, we first make sure that the dependency packages have been introduced to the project's WEB-INF/in the lib directory:

You can directly download the two dependency packages provided by this site:

The source code of UploadServlet is as follows:

package com.w;3codebox.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 files
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // Check if it is a multi-media 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 the memory critical value - If exceeded, a temporary file will be generated and stored in the temporary directory
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // Set the temporary storage directory
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // Set the maximum file upload value
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // Set the 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;
       
         
        // If the directory does not exist, create it
        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) {
                    // 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 in the console
                        System.out.println(filePath);
                        // Save the file to the hard disk
                        item.write(storeFile);
                        request.setAttribute("message",
                            "File upload successful!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "Error Information: " + ex.getMessage());
        }
        // Redirect to message.jsp
        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>

Compile and run the Servlet

Compile the above Servlet UploadServlet and create the required entries in the web.xml file as follows:

<?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.w3codebox.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 use the HTML form you created above to upload a file. When you access in the browser: http://localhost:8080/TomcatTest/upload.jsp, demonstration as follows: