现在很多项目中会将文件储存在oss、obs等云产品中,db只会保存url,有时候需要批量导出这些文件打包成zip等格式并提供给用户下载
HttpServletResponse response = sessionService.getResponse();
//筛选存在于数据库的图片
List<String> dbUrls = List.of("https://a.com/a.jpeg", "https://a.com/b.jpeg", "https://a.com/c.jpeg");
Assert.notEmpty(dbUrls, "相册内容为空");
//处理文件
String zipName = DateUtil.formatLocalDateTimeToString(LocalDateTime.now(), DateUtil.TIME_PATTERN_SESSION) + ".zip";
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + zipName);
response.setCharacterEncoding("utf-8");
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
for (String iUrl : dbUrls) {
URL url = new URL(iUrl);
zipOut.putNextEntry(new ZipEntry(FilenameUtils.getName(iUrl)));
InputStream in = new BufferedInputStream(url.openStream());
zipOut.write(in.readAllBytes());
zipOut.closeEntry();
in.close();
}
} catch (IOException e) {
log.error("导出相册压缩包失败", e);
throw new CustomException("导出相册压缩包失败");
}
参考方案
- 少量URL适用,URL过多可能导致 org.apache.catalina.connector.ClientAbortException: java.io.IOException: 远程主机强迫关闭了一个现有的连接。
- 如果url数量多建议在存储单个文件的时候顺带创建或者更新zip文件并将zip文件上传,需要下载的时候直接返回zip文件避免导出时候一个一个url去请求
- 后台只返回需要导出的url给前端,前端使用jszip进行导出(数量多速度一样会很慢,毕竟要一个一个请求)
版权声明:本文为qq_40735602原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。