JSP學習筆記(四):檔案上傳

來源:互聯網
上載者:User

標籤:java   rtc   相對   瀏覽器   extend   factor   資料   new   final   

  JSP 可以與 HTML form 標籤一起使用,來允許使用者上傳檔案到伺服器。上傳的檔案可以是文字檔或影像檔或任何文檔。我們使用 Servlet 來處理檔案上傳,使用到的檔案有:

  • upload.jsp : 檔案上傳表單。
  • message.jsp : 上傳成功後跳轉頁面。
  • UploadServlet.java : 上傳處理 Servlet。
  • 需要引入的 jar 檔案:commons-fileupload-1.3.2、commons-io-2.5.jar。

  結構如下所示:

1、建立一個檔案上傳表單:

  下面的 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>

2、編寫後台 Servlet:

  以下是 UploadServlet 的原始碼,同於處理檔案上傳,在這之前我們先確保依賴包已經引入到項目的 WEB-INF/lib 目錄下:

  • 下面的執行個體依賴於 FileUpload,所以一定要確保在您的 classpath 中有最新版本的 commons-fileupload.x.x.jar 檔案,可以從 http://commons.apache.org/proper/commons-fileupload/ 下載。
  • FileUpload 依賴於 Commons IO,所以一定要確保在您的 classpath 中有最新版本的 commons-io-x.x.jar 檔案。可以從http://commons.apache.org/proper/commons-io/ 下載。

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

  • commons-fileupload-1.3.2.jar
  • commons-io-2.5.jar

  UploadServlet 的原始碼 如下所示:

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;         // 上傳檔案儲存體目錄    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     /**     * 上傳資料及儲存檔案     */    protected void doPost(HttpServletRequest request,        HttpServletResponse response) throws ServletException, IOException {        // 檢測是否為多媒體上傳        if (!ServletFileUpload.isMultipartContent(request)) {            // 如果不是則停止            PrintWriter writer = response.getWriter();            writer.println("Error: 表單必須包含 enctype=multipart/form-data");            writer.flush();            return;        }         // 配置上傳參數        DiskFileItemFactory factory = new DiskFileItemFactory();        // 設定記憶體臨界值 - 超過後將產生臨時檔案並儲存於臨時目錄中        factory.setSizeThreshold(MEMORY_THRESHOLD);        // 設定臨時儲存目錄        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));         ServletFileUpload upload = new ServletFileUpload(factory);                 // 設定最大檔案上傳值        upload.setFileSizeMax(MAX_FILE_SIZE);                 // 設定最大請求值 (包含檔案和表單資料)        upload.setSizeMax(MAX_REQUEST_SIZE);                // 中文處理        upload.setHeaderEncoding("UTF-8");         // 構造臨時路徑來儲存上傳的檔案        // 這個路徑相對當前應用的目錄        String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;                        // 如果目錄不存在則建立        File uploadDir = new File(uploadPath);        if (!uploadDir.exists()) {            uploadDir.mkdir();        }         try {            // 解析請求的內容提取檔案資料            @SuppressWarnings("unchecked")            List<FileItem> formItems = upload.parseRequest(request);             if (formItems != null && formItems.size() > 0) {                // 迭代表單資料                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);                        // 在控制台輸出檔案的上傳路徑                        System.out.println(filePath);                        // 儲存檔案到硬碟                        item.write(storeFile);                        request.setAttribute("message",                            "檔案上傳成功!");                    }                }            }        } catch (Exception ex) {            request.setAttribute("message",                    "錯誤資訊: " + ex.getMessage());        }        // 跳轉到 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>檔案上傳結果</title></head><body>    <center>        <h2>${message}</h2>    </center></body></html>

3、編譯和運行 Servlet

  編譯上面的 Servlet UploadServlet,並在 web.xml 檔案中建立所需的條目,如下所示:

<?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>

 

JSP學習筆記(四):檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.