Easy Tutorial
❮ Jstl Function Length Jsp Server Response ❯

This is a Chinese to English translation.

JSP can be used with the HTML form tag to allow users to upload files to the server. The uploaded files can be text files, image files, or any document.

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

The structure diagram is 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:

The 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 - tutorialpro.org</title>
</head>
<body>
<h1>File Upload Example - tutorialpro.org</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 the Backend Servlet

The following is the source code for UploadServlet, which is used to process file uploads. Before this, ensure that the dependency packages have been introduced into the WEB-INF/lib directory of the project:

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

The source code for UploadServlet is shown below:

package com.tutorialpro.test;

import java.io.File;
import java.io.IOException;
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;

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "upload";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        String name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    }
                }
                request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }
        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }
}
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, the following code can be used
// @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: The form must include enctype=multipart/form-data");
            writer.flush();
            return;
        }

        // Configure upload parameters
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Set memory threshold - beyond which files are stored in disk
        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 size
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set maximum request size (includes file and form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Handle Chinese characters
        upload.setHeaderEncoding("UTF-8"); 

        // Create a temporary path to store the uploaded file
// This path is relative to the current application's directory
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;

// Create the 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<FileItem> formItems = upload.parseRequest(request);

    if (formItems != null && formItems.size() > 0) {
        // Iterate through the form data
        for (FileItem item : formItems) {
            // Process fields that are not part of 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 upload path of the file to the console
                System.out.println(filePath);
                // Save the file to the 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 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>

Compiling and Running the Servlet

Compile the above Servlet UploadServlet and create the necessary entries in the web.xml file as shown below:

<?xml version="1.0" encoding="UTF-8"?>
&lt;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.tutorialpro.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 upload a file using the HTML form you created above. When you visit: http://localhost:8080/TomcatTest/upload.jsp in your browser, the demo will look like this:

❮ Jstl Function Length Jsp Server Response ❯