springboot下載文件例子

前言

目前網上遍佈springmvc下載文件千篇一律,感覺像是互相抄來抄去,太糟糕了。
本文介紹springboot使用StreamingResponseBody下載文件,使用StreamingResponseBody下載文件使得服務器寫和瀏覽器的讀數據並行化。尤其在大文件下非常有效,速度很快。
我拿miui安裝包來測試,文件大小超過1.5GB,JDK 1.8,springboot 2.2環境。

下載代碼

首先熟悉一下Java的數據流,建議閱讀這篇文章https://www.jianshu.com/p/63d1751d3eac,寫的非常不錯。此時我相信你已經熟練閱讀完這篇文章,並且理解了Java數據流讀寫文件。

下載文件的開始需要定義下載文件的格式

response.setContentType("application/x-zip-compressed");
response.setHeader("Content-Disposition", "attachment; filename=\"chenrui-download.zip\"");

可以給這個文件起一個名字,filename那裏就是起名字的地方。爲了快速驗證結果,filename的變量我寫死了,當然在實際環境裏,你可以根據需要填寫變量進去。

根據文件路徑讀取文件

BufferedInputStream inputStream = 
new BufferedInputStream(new FileInputStream("D:\\miui_MI5_8.11.22_f9ead04910_8.0.zip"));

全部代碼

@GetMapping("/download")
public StreamingResponseBody downlaodFile(HttpServletResponse response) throws FileNotFoundException {
    response.setContentType("application/x-zip-compressed");
    response.setHeader("Content-Disposition", "attachment; filename=\"chenrui-download.zip\"");
    BufferedInputStream inputStream = 
    new BufferedInputStream(new FileInputStream("D:\\miui_MI5_8.11.22_f9ead04910_8.0.zip"));
    return new StreamingResponseBody() {
        @Override
        public void writeTo(OutputStream outputStream) throws IOException {
            int nRead;
            long startTime = System.currentTimeMillis();

            byte[] bytes = new byte[1024];
            while ((nRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
                outputStream.write(bytes, 0, nRead);
            }
            long userTime = System.currentTimeMillis() - startTime;

            System.out.println("使用時間" + userTime);
        }
    };
}
測試與驗證

運行執行時間,單位毫秒
在這裏插入圖片描述
在下載的過程中,我截了一個圖,速度達到了72.5MB每秒,效果還是很可觀的。
在這裏插入圖片描述
在下載文件完成後需要對文件MD5驗證是否一致;
windows下的命令如下。

certutil -hashfile filename MD5
certutil -hashfile filename SHA1
certutil -hashfile filename SHA256

在這裏插入圖片描述

希望指出文章錯誤

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章