SpringBoot根据多阶层创建文件,然后压缩成压缩包进行下载 ...

打印 上一主题 下一主题

主题 910|帖子 910|积分 2730

临时接到一个需求说让根据按照下面的这个图片的结构来打包下载指定位置下的文件到指定位置!
  1. 实现思路:
  2.   1.把已经实现的树形结构的代码进行调用,拿到他的数据进行创建对应的文件夹
  3.   2.因为结构下方的文件没有特别直观的数据库中的关联关系,所以还需要对于管理关系进行梳理
  4.   3.创建好阶级文件,然后调用网上找的工具类打包成为rar压缩包,然后把路劲交给前端进行调用下载
复制代码
调用数据,然后传递给创建文件方法进行实现:
  1. /**
  2. * 打包佐证成果文件,压缩成为压缩包!
  3. *
  4. * @param projectId
  5. * @param departId
  6. */
  7. @ApiOperation(value = "打包佐证成果文件", notes = "佐证与成果-打包佐证成果文件")
  8. @RequestMapping("/exportZip")
  9. public Result<?> exportZip(@RequestParam(name = "projectId", required = false) String projectId, @RequestParam(name = "departId", required = true) String departId) {
  10.     // 获取树形结构
  11.     Result<List<SelectTreeMoneyModel>> loadAllTreeRoot = this.loadAllTreeRoot(projectId, departId);
  12.     // 下载压缩文件,将获取到的树形结构,传递到实现类进行解析跟实现
  13.     String downloadZipFile = downloadZipFile(loadAllTreeRoot, "佐证跟成果", "/");
  14.     return Result.ok(downloadZipFile);
  15. }
复制代码
递归的创建子集文件夹,然后调用工具类进行压缩成为压缩包文件,注:删除文件必须捋清楚然后进行使用,其实不删除也只会在指定的位置生成一份,所以我这边没有进行使用!
  1. /**
  2. * 递归的创建子集文件夹
  3. *
  4. * @param data
  5. * @param rootFile
  6. */
  7. private void mkdirsChild(List<SelectTreeMoneyModel> data, File rootFile) {
  8.     for (SelectTreeMoneyModel datum : data) {
  9.         // 创建一个file实例对象,指向文件路径(存放照片的根目录)
  10.         File childs = new File(rootFile, datum.getTitle());
  11.         if (!childs.exists()) {
  12.             childs.mkdirs();
  13.         }
  14.         // 判断如果下面还有子节点,如果有则调用自身
  15.         if (!datum.isLeaf()) {
  16.             mkdirsChild(datum.getChildren(), childs);
  17.         }
  18.         // 如果下面没有子节点,则进行判断下面是否有附件,如果有附件则进行下载到指定的文件夹内。
  19.         List<ProjectResult> results = iProjectResultService.list(new LambdaQueryWrapper<ProjectResult>().eq(ProjectResult::getTypeId, datum.getKey()));
  20.         if (ObjectUtils.isNotEmpty(results)) {
  21.             for (ProjectResult result : results) {
  22.                 List<ProjectTaskContent> projectTaskContents = projectTaskContentService.list(new LambdaQueryWrapper<ProjectTaskContent>().eq(ProjectTaskContent::getResultId, result.getId()));
  23.                 for (ProjectTaskContent projectTaskContent : projectTaskContents) {
  24.                     // 判断附件表不是空的,则进行下载文件到对应的文件夹下
  25.                     if (ObjectUtils.isNotEmpty(projectTaskContents)) {
  26.                         RestTemplate restTemplate = new RestTemplate();
  27.                         // 配置文件进行读取
  28.                         try {
  29.                             ResponseEntity responseEntity = restTemplate.exchange(url + projectTaskContent.getFilePath(), HttpMethod.GET, null, byte[].class);
  30.                             byte[] fileContent = (byte[]) responseEntity.getBody();
  31.                             // 利用 File 对象,然后使用 getName() 方法获取文件名(不包括路径)。
  32.                             File file = new File(projectTaskContent.getName());
  33.                             String filenameWithoutPrefix = file.getName();
  34.                             Files.write(Paths.get(childs + "\" + filenameWithoutPrefix), fileContent);
  35.                         } catch (IOException e) {
  36.                             e.getMessage();
  37.                             throw new RuntimeException(e);
  38.                         }
  39.                     }
  40.                 }
  41.             }
  42.         }
  43.     }
  44. }
  45. /**
  46. * 下载压缩文件
  47. *
  48. * @param data       数据集合【key:分类名称,value:照片信息集合(key:照片名称,value:照片下载路径)】
  49. * @param fileStr    照片存放的文件路径
  50. * @param zipFileStr 压缩文件的路径(加后缀名)
  51. */
  52. public String downloadZipFile(Result<List<SelectTreeMoneyModel>> data, String fileStr, String zipFileStr) {
  53.     File rootFile = null;
  54.     String folderPath = null;
  55.     try {
  56.         // 遍历传递进来的数据,然后根据传入的数据进行创建文件夹
  57.         for (SelectTreeMoneyModel selectTreeMoneyModel : data.getResult()) {
  58.             // 创建一个file实例对象,指向文件路径(存放照片的根目录)
  59.             zipFileStr = folderUri + selectTreeMoneyModel.getTitle();
  60.             folderPath = selectTreeMoneyModel.getTitle();
  61.             rootFile = new File(zipFileUri + selectTreeMoneyModel.getTitle());
  62.             if (!rootFile.exists()) {
  63.                 // 创建新文件夹,可以多层(mkdir()创建新文件夹,只能创建一层)
  64.                 rootFile.mkdirs();
  65.             }
  66.             // 根据判断递归的创建文件夹,如果是false则有子集
  67.             if (!selectTreeMoneyModel.isLeaf()) {
  68.                 mkdirsChild(selectTreeMoneyModel.getChildren(), rootFile);
  69.             }
  70.         }
  71.         // 创建文件输出流(zip流对象)【实际创建了zip文件,0kb】
  72.         FileOutputStream fos1 = new FileOutputStream(new File(zipFileStr + ".zip"));
  73.         // 压缩法
  74.         toZip1(rootFile, fos1, true);
  75.         //TODO  删除文件和压缩文件,要保证每次压缩只保存一份最新的存在。 因为是删除文件,所以要慎用
  76.         //delFolder(folderUri + folderPath);
  77.         //delFolder(zipFileStr);
  78.     } catch (IOException e) {
  79.         e.printStackTrace();
  80.     }
  81.     // 拼接返回的压缩包地址
  82.     String urlResult = url + folderPath + ".zip";
  83.     return urlResult;
  84. }
  85. /**
  86. * 删除文件夹
  87. *
  88. * @param folderPath 文件夹完整绝对路径
  89. */
  90. public static void delFolder(String folderPath) {
  91.     try {
  92.         // 删除目录下所有内容
  93.         delAllFile(folderPath);
  94.         File myFilePath = new File(folderPath);
  95.         //删除空文件夹
  96.         myFilePath.delete();
  97.     } catch (Exception e) {
  98.         e.printStackTrace();
  99.     }
  100. }
  101. /**
  102. * 删除指定文件夹下所有文件
  103. *
  104. * @param path 文件夹完整绝对路径
  105. */
  106. public static boolean delAllFile(String path) {
  107.     boolean bea = false;
  108.     File file = new File(path);
  109.     if (!file.exists()) {
  110.         return bea;
  111.     }
  112.     if (!file.isDirectory()) {
  113.         return bea;
  114.     }
  115.     //
  116.     String[] tempList = file.list();
  117.     File temp;
  118.     if (tempList != null) {
  119.         for (String var : tempList) {
  120.             // separator 代替文件或文件夹路径的斜线或反斜线,防止跨平台出现错误
  121.             if (path.endsWith(File.separator)) {
  122.                 temp = new File(path + var);
  123.             } else {
  124.                 temp = new File(path + File.separator + var);
  125.             }
  126.             if (temp.isFile()) {
  127.                 temp.delete();
  128.             }
  129.             if (temp.isDirectory()) {
  130.                 //先删除文件夹里面的文件
  131.                 delAllFile(path + "/" + var);
  132.                 //再删除空文件夹
  133.                 delFolder(path + "/" + var);
  134.                 bea = true;
  135.             }
  136.         }
  137.     }
  138.     return bea;
  139. }
  140. /**
  141. * 压缩的递归方法
  142. *
  143. * @param sourceFile       源文件
  144. * @param zos              zip输出流
  145. * @param fileName         源文件的名称
  146. * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
  147. *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  148. */
  149. private void compress(File sourceFile, ZipOutputStream zos, String fileName, boolean keepDirStructure) throws IOException {
  150.     byte[] buf = new byte[2 * 1024];
  151.     // 判断是否是一个文件
  152.     if (sourceFile.isFile()) {
  153.         // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
  154.         zos.putNextEntry(new ZipEntry(fileName));
  155.         // 创建文件(即某张图片)的输入流
  156.         try (FileInputStream in = new FileInputStream(sourceFile)) {
  157.             int len;
  158.             // read方法:每调用一次就从FileInputStream流中读取一个字节,并返回下一个数据字节,若已到达末尾,就返回-1。
  159.             while ((len = in.read(buf, 0, buf.length)) != -1) {
  160.                 zos.write(buf, 0, len);
  161.             }
  162.             // 实际写入到了zip输出流的zip实体中,还没写到文件中【zip文件时0kb,不能打开,因为流没有关闭】
  163.             zos.closeEntry();
  164.         } catch (IOException e) {
  165.             throw new IOException(e);
  166.         }
  167.     } else {
  168.         // 源文件时目录
  169.         // 获取该目录下所有文件和目录的绝对路径
  170.         File[] listFiles = sourceFile.listFiles();
  171.         // 空目录
  172.         if (listFiles == null || listFiles.length == 0) {
  173.             // 需要保留原来的文件结构时,需要对空文件夹进行处理
  174.             if (keepDirStructure) {
  175.                 // 空文件夹的处理
  176.                 zos.putNextEntry(new ZipEntry(fileName + "/"));
  177.                 // 没有文件,不需要文件的copy
  178.                 zos.closeEntry();
  179.             }
  180.         } else {
  181.             // 非空目录
  182.             for (File file : listFiles) {
  183.                 if (keepDirStructure) {
  184.                     // 注意:getName()仅得到最后一层的名字,不是路径,所以要加“/”,不然所有文件都跑到压缩包根目录下了
  185.                     compress(file, zos, fileName + "/" + file.getName(), true);
  186.                 } else {
  187.                     compress(file, zos, file.getName(), false);
  188.                 }
  189.             }
  190.         }
  191.     }
  192. }
  193. /**
  194. * 压缩成ZIP 方法1:保留多级目录结构
  195. *
  196. * @param sourceFile       照片存放路径
  197. * @param out              压缩文件输出流
  198. * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
  199. *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  200. */
  201. public void toZip1(File sourceFile, OutputStream out, boolean keepDirStructure) throws IOException {
  202.     long start = System.currentTimeMillis();
  203.     // 创建压缩输出流,java7的新语法:Try-with-resources,会确保异常抛出或者try代码块结束时close流【该流必须实现AutoCloseable类】(若是java7之前的版本,则不会生效)
  204.     try (ZipOutputStream zos = new ZipOutputStream(out)) {
  205.         // 压缩
  206.         compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
  207.         long end = System.currentTimeMillis();
  208.         System.out.println("压缩完成,耗时:" + (end - start) + " ms");
  209.     } catch (IOException e) {
  210.         throw new IOException(e);
  211.     }
  212. }
复制代码
最后的实现结果


  1.       总结: 主要还是要理清楚你的层级关系,
  2.       1.然后在递归的时候一定要递归到最底层,然后根据最底层的数据查找跟附件表有关系的ID进行查找,然后将有关系的文件下载到指定的文件夹下,
  3.       2.然后打包成为压缩包这种实现直接可以进行百度查找到适合自己的工具类,如果不是直接适用,可以进行修改工具类的方法进行适配。
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大号在练葵花宝典

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表