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

在这里插入图片描述

希望指出文章错误

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