1. 程式人生 > 其它 >HttpServletResponse簡單應用之檔案下載

HttpServletResponse簡單應用之檔案下載

宣告

本文部分內容參考自其他作者原創文章,僅供個人學習留檔,特此宣告

參考文章連結

(1條訊息) B站---【狂神說Java】JavaWeb入門到實戰---筆記_夜裡的雨的部落格-CSDN部落格_狂神說java筆記

HttpServletResponse簡單應用之檔案下載

這一節的核心在於header設定某key為 attachment;filename=

即設定想辦法讓瀏覽器能夠支援(Content-Disposition)下載我們需要的東西,中文檔名URLEncoder.encode編碼,否則有可能亂碼

resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

1.首先思考一下下載檔案需要經歷哪些步驟?

要獲取下載檔案的路徑

要下載檔案的檔名是什麼?

想辦法讓瀏覽器能夠支援下載我們想要的檔案(設定)

獲取下載檔案的輸入流

建立緩衝區;獲取OutputStream物件;將FileOutputStream流寫入到buffer緩衝區

使用OutputStream將緩衝區中的資料輸出到客戶端!


2.接下來寫程式,將用於下載的圖片檔案放到資原始檔夾下

1、程式碼

1.用於下載檔案的FileServlet程式碼

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 獲取下載檔案的路徑
        String realPath = "E:\\environment\\Maven\\MavenStudy\\javaweb-002-servlet\\response\\target\\classes\\1.png";
        System.out.println("下載檔案的路徑:" + realPath);
        // 2. 下載的檔名是什麼?
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        // 3. 設定想辦法讓瀏覽器能夠支援(Content-Disposition)下載我們需要的東西,中文檔名URLEncoder.encode編碼,否則有可能亂碼
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 4. 獲取下載檔案的輸入流
        FileInputStream in = new FileInputStream(realPath);
        // 5. 建立緩衝區
        int len = 0;
        byte[] buffer = new byte[1024];
        // 6. 獲取OutputStream物件
        ServletOutputStream out = resp.getOutputStream();
        // 7. 將FileOutputStream流寫入到buffer緩衝區,使用OutputStream將緩衝區中的資料輸出到客戶端!
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        //8.關閉所有流
        in.close();
        out.close();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.用於註冊對映路徑的web.xml程式碼

<servlet>
    <servlet-name>filedown</servlet-name>
    <servlet-class>com.xy.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>filedown</servlet-name>
    <url-pattern>/down</url-pattern>
</servlet-mapping>

3.用於防止打包內容不全的pom.xml程式碼

<!--在pom.xml的<build>中配置<resources>,來防止我們資源匯出失敗的問題-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                <include>**/*.png</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

2、程式碼測試

進入測試網頁 http://localhost:8080/response/down 之後如下圖所示自動下載

開啟下載好的檔案看一下,下載成功了


3、一些問題(解決)

1.打包的時候不打包.png檔案

解決方法依舊是在pom.xml檔案裡新增resource,如下(以後此類問題都可以這樣處理)

<resource>
    <directory>src/main/resources</directory>
    <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
        <include>**/*.png</include>
    </includes>
</resource>

2.找不到想要下載資源的路徑

解決方法是可以把路徑寫死成檔案的絕對路徑

解決步驟如下:

  • 我們用一個相對簡單的方法獲得檔案的絕對路徑

    • 找到想要下載的那個檔案(打包好的)

    • 右擊 --> copy path --> absolute path

    • 把這個路徑複製到FileServlet程式碼中即可(把路徑寫死)

      // 1. 要獲取下載檔案的路徑
      String realPath = "E:\\environment\\Maven\\MavenStudy\\javaweb-002-servlet\\response\\target\\classes\\1.png";
      

3.如何用一個簡單方法獲取下載檔名?(以下方法記住即可,常用)

首先我們觀察一下要下載的檔案的存在路徑

//1.要獲取下載檔案的路徑
String realPath = "E:\\environment\\Maven\\MavenStudy\\javaweb-002-servlet\\response\\target\\classes\\1.png";

很明顯,下載檔案的realPath的最後一個 \ \ 後邊的字串就是下載的檔名

E:\\environment\\Maven\\MavenStudy\\javaweb-002-servlet\\response\\target\\classes\\1.png

最後一個 \ \ 後邊的字串為 1.png 這就是下載檔案的檔名

所以我們用下邊這行程式碼來獲取下載檔名

//2.下載的檔名是什麼?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);