JSP 文件上傳

JSP 可以與 HTML form 標(biāo)簽一起使用,來(lái)允許用戶上傳文件到服務(wù)器。上傳的文件可以是文本文件或圖像文件或任何文檔。

本章節(jié)我們使用 Servlet 來(lái)處理文件上傳,使用到的文件有:

  • upload.jsp : 文件上傳表單。

  • message.jsp : 上傳成功后跳轉(zhuǎn)頁(yè)面。

  • UploadServlet.java : 上傳處理 Servlet。

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

結(jié)構(gòu)圖如下所示:

圖片.png

接下來(lái)我們?cè)敿?xì)介紹。

創(chuàng)建一個(gè)文件上傳表單

下面的 HTML 代碼創(chuàng)建了一個(gè)文件上傳表單。以下幾點(diǎn)需要注意:

  • 表單 method 屬性應(yīng)該設(shè)置為 POST 方法,不能使用 GET 方法。

  • 表單 enctype 屬性應(yīng)該設(shè)置為 multipart/form-data.

  • 表單 action 屬性應(yīng)該設(shè)置為在后端服務(wù)器上處理文件上傳的 Servlet 文件。下面的示例使用了 UploadServlet Servlet 來(lái)上傳文件。

  • 上傳單個(gè)文件,您應(yīng)該使用單個(gè)帶有屬性 type="file" 的 <input .../> 標(biāo)簽。為了允許多個(gè)文件上傳,請(qǐng)包含多個(gè) name 屬性值不同的 input 標(biāo)簽。輸入標(biāo)簽具有不同的名稱(chēng)屬性的值。瀏覽器會(huì)為每個(gè) input 標(biāo)簽關(guān)聯(lián)一個(gè)瀏覽按鈕。

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>文件上傳示例 - 菜鳥(niǎo)教程</title>
</head>
<body>
<h1>文件上傳示例 - 菜鳥(niǎo)教程</h1>
<form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
    選擇一個(gè)文件:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="上傳" />
</form>
</body>
</html>

編寫(xiě)后臺(tái) Servlet

以下是 UploadServlet 的源代碼,同于處理文件上傳,在這之前我們先確保依賴包已經(jīng)引入到項(xiàng)目的 WEB-INF/lib 目錄下:

你可以直接下載本站提供的兩個(gè)依賴包:

UploadServlet 的源代碼 如下所示:

package com.nhooo.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
 */
// 如果不配置 web.xml ,可以使用下面的代碼
// @WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // 上傳文件存儲(chǔ)目錄
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // 上傳配置
    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
 
    /**
     * 上傳數(shù)據(jù)及保存文件
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // 檢測(cè)是否為多媒體上傳
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是則停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表單必須包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
 
        // 配置上傳參數(shù)
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 設(shè)置內(nèi)存臨界值 - 超過(guò)后將產(chǎn)生臨時(shí)文件并存儲(chǔ)于臨時(shí)目錄中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 設(shè)置臨時(shí)存儲(chǔ)目錄
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // 設(shè)置最大文件上傳值
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // 設(shè)置最大請(qǐng)求值 (包含文件和表單數(shù)據(jù))
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // 中文處理
        upload.setHeaderEncoding("UTF-8"); 
        // 構(gòu)造臨時(shí)路徑來(lái)存儲(chǔ)上傳的文件
        // 這個(gè)路徑相對(duì)當(dāng)前應(yīng)用的目錄
        String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
       
         
        // 如果目錄不存在則創(chuàng)建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
 
        try {
            // 解析請(qǐng)求的內(nèi)容提取文件數(shù)據(jù)
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // 迭代表單數(shù)據(jù)
                for (FileItem item : formItems) {
                    // 處理不在表單中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制臺(tái)輸出文件的上傳路徑
                        System.out.println(filePath);
                        // 保存文件到硬盤(pán)
                        item.write(storeFile);
                        request.setAttribute("message",
                            "文件上傳成功!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "錯(cuò)誤信息: " + ex.getMessage());
        }
        // 跳轉(zhuǎn)到 message.jsp
        getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);
    }
}

message.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>文件上傳結(jié)果</title>
</head>
<body>
    <center>
        <h2>${message}</h2>
    </center>
</body>
</html>

編譯和運(yùn)行 Servlet

編譯上面的 Servlet UploadServlet,并在 web.xml 文件中創(chuàng)建所需的條目,如下所示:

<?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.nhooo.test.UploadServlet</servlet-class>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/TomcatTest/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

現(xiàn)在嘗試使用您在上面創(chuàng)建的 HTML 表單來(lái)上傳文件。當(dāng)您在瀏覽器中訪問(wèn):http://localhost:8080/TomcatTest/upload.jsp ,演示如下所示:

圖片.png

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清