文件下载接口 - Spring Boot
@GetMapping('download/{filename}')
public void download(@PathVariable('filename') String filename, HttpServletResponse response) throws IOException {
File file = new File(uploadFolder + filename);
if (!file.exists()) {
file = new File(uploadFolder + '1.jpg');
}
response.setHeader('Content-Disposition', 'attachment;filename='' + filename + ''');
response.setContentType('application/octet-stream');
response.setContentLength((int) file.length());
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ServletOutputStream sos = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(sos)) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
}
}
优化点:
-
使用 try-with-resources 语法糖,自动关闭流,避免出现流没有关闭的情况。
-
使用缓冲流,提高读写文件的效率。
-
设置 Content-Type 为 application/octet-stream,表示下载的是二进制文件,避免浏览器打开文件。
-
设置 Content-Length,告诉浏览器下载文件的大小,避免下载过程中出现异常。
-
使用字节数组缓冲区进行读写,提高效率。
代码解释:
-
使用
@GetMapping('download/{filename}')注解定义文件下载接口,参数filename代表要下载的文件名。 -
获取文件对象,如果文件不存在,则使用默认图片。
-
设置响应头:
Content-Disposition:用于告诉浏览器将响应内容作为附件下载,并指定文件名。Content-Type:指定文件类型为二进制流。Content-Length:指定文件大小,以便浏览器显示进度条。
-
使用
try-with-resources语法糖自动关闭流,确保资源被正确关闭。 -
使用缓冲流
BufferedInputStream和BufferedOutputStream提高读写效率。 -
使用字节数组缓冲区读取文件内容,并将内容写入响应输出流。
-
最后,使用
bos.flush()确保所有数据都被写入输出流。
原文地址: https://www.cveoy.top/t/topic/oCpk 著作权归作者所有。请勿转载和采集!