Servlet file upload


Release date:2023-12-14 Update date:2023-12-14 Editor:admin View counts:80

Label:

Servlet file upload

Servlet can be used with the HTML form tag to allow users to upload files tothe server. The uploaded file can be a text file or an image file or any document.

The files used in this article are:

  • upload.jsp : File upload form

  • message.jsp : Jump to the page after the upload is successful

  • UploadServlet.java : Upload processing Servlet.

  • The jar file that needs to be introduced: commons-fileupload-1.3.2、commons-io-2.5.jar .

The structure diagram is as follows:

Image0

Note: Servlet3.0 has built-in file upload feature, so developers no longer need to import Commons FileUpload components into the project.

Next, we will introduce it 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 property should be set to the POST method and cannot use the GET method.

  • Form enctype property should be set to multipart/form-data .

  • Form action property should be set to handle Servlet files uploaded by files on the back-end server. The following example uses UploadServlet Servlet to upload files.

  • To upload a single file, you should use a single < input… / > tag with theattribute type= “file”. To allow multiple file uploads, include multiple name tags with different input attribute values. Enter a value for the labelwith a different name attribute. The browser associates a browse button foreach input tag.

upload.jsp : The 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 - Rookie Tutorial</title>
</head>
<body>
<h1>File Upload Example - Rookie Tutorial</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 the same as dealing with file upload. Before that, let’s make sure that the dependency package has been introduced into the project’s WEB-INF/lib directory:

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

The UploadServlet source code is as follows:

package com.runoob.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;

    // 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 multimedia 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 - if exceeded, temporary files will be generated and stored in the temporary 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);

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

        // Construct a temporary path to store uploaded files
        // This path is relative to the directory of the current application
        String uploadPath = request.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 requested content and extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // Iteration represents single data
                for (FileItem item : formItems) {
                    // Process fields that are 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 file upload path in the console
                        System.out.println(filePath);
                        // Save files to hard drive
                        item.write(storeFile);
                        request.setAttribute("message",
                            "File upload successful!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "error message: " + ex.getMessage());
        }
        // Jump to message.jsp
        request.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 results</title>
</head>
<body>
    <center>
        <h2>${message}</h2>
    </center>
</body>
</html>

Compile and run Servlet

Compile the Servlet UploadServlet above, and in the web.xml create the required entries in the 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.runoob.test.UploadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/TomcatTest/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

Now try uploading the file using the HTML form you created above. When you visit: http://localhost:8080/TomcatTest/upload.jsp in the browser, the demonstration is as follows:

Image1

Powered by TorCMS (https://github.com/bukun/TorCMS).