Servlet下載檔案


這裡是一個從伺服器下載檔案的簡單例子。假設想要下載專案根目錄中的home.jsp檔案。如果有任何jarzip檔案,可以直接提供該檔案的連結,不必編寫程式來下載這樣的檔案。 但是如果有任何java檔案或者jsp檔案等,則需要編寫一個程式來下載這類檔案。

在servlet中從伺服器下載檔案的範例

開啟Eclipse,建立一個動態Web專案:ServletDownloadFile,其完整的目錄結構如下所示 -

在這個例子中,建立了三個檔案:

  • index.html - 首頁入口
  • DownloadServlet.java - 處理要下載的檔案並向用戶端輸出檔案下載。
  • web.xml - 此組態檔案向伺服器提供有關servlet的資訊。

檔案:index.html

該檔案提供了一個下載檔案的連結。參考下面程式碼 -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet下載檔案範例</title>
</head>
<body>
<div style="margin:auto;text-align:center;">
    <a href="DownloadJSP">下載JSP檔案</a>
</div>
</body>
</html>

檔案:DownloadServlet.java

這是一個實現servlet的檔案,讀取檔案的內容並將其寫入流中作為響應傳送給用戶端。因此需要通知伺服器將內容型別設定為:APPLICATION/OCTET-STREAM

package com.yiibai;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String filepath = request.getSession().getServletContext().getRealPath("");
        String filename = "home.jsp";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        FileInputStream fileInputStream = new FileInputStream(filepath + filename);

        int i = 0;
        while ((i = fileInputStream.read()) != -1) {
            out.write(i);
        }
        fileInputStream.close();
        out.close();
    }

}

檔案:web.xml

此組態檔案向伺服器提供有關servlet的資訊。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>ServletDownloadFile</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>DownloadServlet</servlet-name>
        <servlet-class>com.yiibai.DownloadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/DownloadJSP</url-pattern>
    </servlet-mapping>

</web-app>

在編寫上面程式碼後,部署此Web應用程式(在專案名稱上點選右鍵->」Run On Server…」),開啟瀏覽器存取URL: http://localhost:8080/ServletDownloadFile/ ,如果沒有錯誤,應該會看到以下結果 -

點選上頁面中的「下載JSP檔案」連結,可以看到以下結果 -