当前位置:   article > 正文

Spring Boot 文件通过zip压缩包 批量下载_springboot3.2 实现zip下载

springboot3.2 实现zip下载

最近项目中新增了一个需求:要求批量下载之前信息导出的word 文件,也就是批量下载。

数据是保存在ES 中,导出word 的功能也是写好的。

我的思路:

  1. 传入数据ID分别导出word 文件到服务器某个文件夹。
  2. 根据文件地址将所有文件打包成zip文件到服务器某个地址
  3. 根据zip文件地址进行下载

存在问题:

批量导出word 文档,由于数据量大可能会非常耗时。

解决:

采用的异步方式分别导出每一个word文件,大大节省了文件导出效率。

具体方法参考:Spring boot 入门教程- 使用异步线程池

使用这种方法虽然提高文件导出效率,但是所有文件导出完成时间无法控制。

这里采用如下方法

  1. List<CompletableFuture<Map<String, String>>> list = new ArrayList<>();
  2. for (String sourceCode : sourceCodes.split(",")) {
  3. CompletableFuture<Map<String, String>> future = favoriteService.exportFavoriteItemWordFile(sourceCode);
  4. list.add(future);
  5. }
  6. CompletableFuture<Map<String, String>>[] completableFutures = list.toArray(new CompletableFuture[list.size()]);
  7. CompletableFuture.allOf(completableFutures).join();

 CompletableFuture.allOf().join(); 等待所有线程任务结束

文件导出方法调用:

  1. @Async
  2. @Override
  3. public CompletableFuture<Map<String, String>> exportFavoriteItemWordFile(String sourceCode) throws IOException, URISyntaxException, InterruptedException {
  4. Map<String, String> result = esDetailedService.exportDetailInfoDoc(sourceCode);
  5. return CompletableFuture.completedFuture(result);
  6. }

这里result 返回了文件在服务器上的存路径。可以通过future.get().get("url") 获取。

word 导出实现参考:使用POI 导出word模板文件

剩下的就是文件打包成zip 的解决了,这里提供一个工具类:

  1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.zip.ZipEntry;
  5. import java.util.zip.ZipOutputStream;
  6. /**
  7. * @BelongsProject: exchange
  8. * @BelongsPackage: com.elens.util
  9. * @Author: xuweichao
  10. * @CreateTime: 2019-06-04 15:51
  11. * @Description: 文件压缩工具类
  12. */
  13. public class ZipUtil {
  14. private static final int BUFFER_SIZE = 2 * 1024;
  15. /**
  16. * 压缩成ZIP 方法1
  17. *
  18. * @param srcDir 压缩文件夹路径
  19. * @param out 压缩文件输出流
  20. * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
  21. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  22. * @throws RuntimeException 压缩失败会抛出运行时异常
  23. */
  24. public static void toZip(String srcDir, OutputStream out, boolean keepDirStructure)
  25. throws RuntimeException {
  26. long start = System.currentTimeMillis();
  27. ZipOutputStream zos = null;
  28. try {
  29. zos = new ZipOutputStream(out);
  30. File sourceFile = new File(srcDir);
  31. compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
  32. long end = System.currentTimeMillis();
  33. System.out.println("压缩完成,耗时:" + (end - start) + " ms");
  34. } catch (Exception e) {
  35. throw new RuntimeException("zip error from ZipUtils", e);
  36. } finally {
  37. if (zos != null) {
  38. try {
  39. zos.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. /**
  47. * 压缩成ZIP 方法2
  48. *
  49. * @param srcFiles 需要压缩的文件列表
  50. * @param out 压缩文件输出流
  51. * @throws RuntimeException 压缩失败会抛出运行时异常
  52. */
  53. public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
  54. long start = System.currentTimeMillis();
  55. ZipOutputStream zos = null;
  56. try {
  57. zos = new ZipOutputStream(out);
  58. for (File srcFile : srcFiles) {
  59. byte[] buf = new byte[BUFFER_SIZE];
  60. zos.putNextEntry(new ZipEntry(srcFile.getName()));
  61. int len;
  62. FileInputStream in = new FileInputStream(srcFile);
  63. while ((len = in.read(buf)) != -1) {
  64. zos.write(buf, 0, len);
  65. }
  66. zos.closeEntry();
  67. in.close();
  68. }
  69. long end = System.currentTimeMillis();
  70. System.out.println("压缩完成,耗时:" + (end - start) + " ms");
  71. } catch (Exception e) {
  72. throw new RuntimeException("zip error from ZipUtils", e);
  73. } finally {
  74. if (zos != null) {
  75. try {
  76. zos.close();
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. }
  82. }
  83. /**
  84. * 递归压缩方法
  85. *
  86. * @param sourceFile 源文件
  87. * @param zos zip输出流
  88. * @param name 压缩后的名称
  89. * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
  90. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  91. * @throws Exception
  92. */
  93. private static void compress(File sourceFile, ZipOutputStream zos, String name,
  94. boolean keepDirStructure) throws Exception {
  95. byte[] buf = new byte[BUFFER_SIZE];
  96. if (sourceFile.isFile()) {
  97. // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
  98. zos.putNextEntry(new ZipEntry(name));
  99. // copy文件到zip输出流中
  100. int len;
  101. FileInputStream in = new FileInputStream(sourceFile);
  102. while ((len = in.read(buf)) != -1) {
  103. zos.write(buf, 0, len);
  104. }
  105. // Complete the entry
  106. zos.closeEntry();
  107. in.close();
  108. } else {
  109. File[] listFiles = sourceFile.listFiles();
  110. if (listFiles == null || listFiles.length == 0) {
  111. // 需要保留原来的文件结构时,需要对空文件夹进行处理
  112. if (keepDirStructure) {
  113. // 空文件夹的处理
  114. zos.putNextEntry(new ZipEntry(name + "/"));
  115. // 没有文件,不需要文件的copy
  116. zos.closeEntry();
  117. }
  118. } else {
  119. for (File file : listFiles) {
  120. // 判断是否需要保留原来的文件结构
  121. if (keepDirStructure) {
  122. // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
  123. // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
  124. compress(file, zos, name + "/" + file.getName(), keepDirStructure);
  125. } else {
  126. compress(file, zos, file.getName(), keepDirStructure);
  127. }
  128. }
  129. }
  130. }
  131. }
  132. public static void main(String[] args) throws Exception {
  133. /** 测试压缩方法1 */
  134. FileOutputStream fos1 = new FileOutputStream(new File("H:\\xuweichao.zip"));
  135. ZipUtil.toZip("H:\\docTmp", fos1, true);
  136. // /** 测试压缩方法2 */
  137. // List<File> fileList = new ArrayList<>();
  138. // fileList.add(new File("H:\\docTmp\\36c194f1-6d69-4114-a26e-c6170af.doc"));
  139. // fileList.add(new File("H:\\docTmp\\303e9dd9-6270-4968-95c8-13c660a.doc"));
  140. // fileList.add(new File("H:\\docTmp\\545a857a-2f3b-487c-8b21-a58da9d.doc"));
  141. // fileList.add(new File("H:\\docTmp\\ce608bff-f00d-4436-9c30-da73f70.doc"));
  142. // FileOutputStream fos2 = new FileOutputStream(new File("H:\\docTmp\\xuweichao.zip"));
  143. // ZipUtil.toZip(fileList, fos2);
  144. }
  145. }

调用

  1. String zipFileName = "收藏夹人物信息打包-" + System.currentTimeMillis() + ".zip";
  2. String zipFilePathName = words2ZipTmpDir + zipFileName;
  3. File zipfile = new File(zipFilePathName);
  4. if (!zipfile.getParentFile().exists()) {
  5. zipfile.getParentFile().mkdirs();
  6. }
  7. FileOutputStream fos = new FileOutputStream(zipfile);
  8. ZipUtil.toZip(zipFiles, fos);
List<File> zipFiles = new ArrayList<>();

zipFiles :需要打包的文件集合.

然后根据zipFilePathName 下载zip文件即可。

这里只提供了实现思路和关键代码,有问题欢迎反馈交流。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/307917
推荐阅读
相关标签
  

闽ICP备14008679号