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

Subida de archivos de JSP

JSP 可以与 HTML form 标签一起使用,来允许用户上传文件到服务器。上传的文件可以是文本文件或图像文件或任何文档。

本章节我们使用 Servlet 来处理文件上传,使用到的文件有:

  • upload.jsp : 文件上传表单。

  • message.jsp : 上传成功后跳转页面。

  • UploadServlet.java : 上传处理 Servlet。

  • 需要引入的 jar 文件:commons-fileupload-1.3.2、commons-io-2.5.jar。

结构图如下所示:


接下来我们详细介绍。

创建一个文件上传表单

下面的 HTML 代码创建了一个文件上传表单。以下几点需要注意:

  • 表单 method 属性应该设置为 POST 方法,不能使用 GET 方法。

  • 表单 enctype 属性应该设置为 multipart/form-data.

  • 表单 action 属性应该设置为在后端服务器上处理文件上传的 Servlet 文件。下面的示例使用了 UploadServlet Servlet 来上传文件。

  • 上传单个文件,您应该使用单个带有属性 type="file" 的 <input .../> 标签。为了允许多个文件上传,请包含多个 name 属性值不同的 input 标签。输入标签具有不同的名称属性的值。浏览器会为每个 input 标签关联一个浏览按钮。

upload.jsp 文件代码如下:

<%@ 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>文件上传示例 - 基础教程网</title>
</head>
<body>
<h1>文件上传示例 - 基础教程网</h1>
<form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
    选择一个文件:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="上传" />
</form>
</body>
</html>

编写后台 Servlet

以下是 UploadServlet 的源代码,用于处理文件上传,在这之前我们先确保依赖包已经引入到项目的 WEB-INF/lib 目录下:

你可以直接下载本站提供的两个依赖包:

UploadServlet 的源代码如下所示:

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;
 
/**
 * Clase de implementación de Servlet ServletImplementationClass UploadServlet
 */
// Si no se configura web.xml, se puede usar el siguiente código
// @WebServlet("/UploadServlet)
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // Directorio de almacenamiento de archivos de subida
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // Configuración de subida
    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
 
    /**
     * Subir datos y guardar archivos
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // Detectar si es una carga multimedia
        if (!ServletFileUpload.isMultipartContent(request)) {
            // Si no, detener}}
            PrintWriter writer = response.getWriter();
            writer.println("Error: La formulario debe contener enctype=multipart/form-data");
            writer.flush();
            return;
        }
 
        // Configurar parámetros de subida
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Establecer el valor crítico de memoria - Después de lo cual se generará un archivo temporal y se almacenará en el directorio temporal
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // Establecer el directorio de almacenamiento temporal
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // Establecer el valor máximo de subida de archivo
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // Establecer el valor máximo de solicitud (incluso datos de archivo y formulario)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // Manejo de caracteres chinos
        upload.setHeaderEncoding("UTF-8"); 
        // Construir una ruta temporal para almacenar los archivos subidos
        // Esta ruta es relativa al directorio de la aplicación actual
        String uploadPath = getServletContext().getRealPath("/)", + File.separator + UPLOAD_DIRECTORY;
       
         
        // Si el directorio no existe, crearlo
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
 
        try {
            // Analizar el contenido de la solicitud para extraer datos de archivos
            @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());
        }
        // Jump to message.jsp
        getServletContext().getRequestDispatcher("/message.jsp
                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>

Ahora intente usar el formulario HTML creado anteriormente para subir archivos. Al acceder al navegador desde: http://localhost:8080/TomcatTest/upload.jsp, ejemplo a continuación: