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

在这里插入图片描述

希望指出文章错误

Spring Boot中,下载文件到浏览器通常通过HTTP响应头控制Content-Disposition来实现。你可以创建一个简单的Controller方法,将文件作为响应体返回,并设置合适的头信息。以下是一个基本示例: ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @GetMapping("/download-file") public ResponseEntity<ByteArrayResource> downloadFile(@RequestParam("file") MultipartFile file) throws IOException { // 检查文件是否上传成功 if (file.isEmpty()) { return ResponseEntity.badRequest().build(); } // 将MultipartFile转换为File对象 Path filePath = Paths.get("path/to/save/downloaded/file", file.getOriginalFilename()); Files.write(filePath, file.getBytes()); // 创建 ByteArrayResource 对象表示文件内容 ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(filePath)); // 设置HTTP响应头,指定文件名和浏览器下载属性 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("filename", file.getOriginalFilename()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 返回 ResponseEntity,包含资源和响应头 return ResponseEntity.ok() .headers(headers) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } ``` 在这个例子中,用户通过HTTP GET请求访问`/download-file`并传递文件字段(file),服务器会将文件保存到指定路径,然后创建一个可以流式传输给客户端的ByteArrayResource。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值