Vue实现前端本地打包为一个zip文件

1、应用场景:打包批量下载的二维码图片
2、实际后端返回数据格式:图片链接数组集合,每个图片链接打开都是一张二维码图片
3、代码实现如下:

元素代码

<el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="downloadCode">
          下载二维码
</el-button>

js代码
第一步安装依赖包
npm i axios, JSZip, FileSaver -s

<script>
// 引入依赖包
import JSZip from "jszip";
import FileSaver from "file-saver";
import axios from "axios";
// 方法封装
const getFile = (url) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "get",
      url,
      responseType: "blob",
    })
      .then((data) => {
        resolve(data.data);
      })
      .catch((error) => {
        reject(error.toString());
      });
   });
  };
// 方法定义
filesToRar(urlData) {
    const zip = new JSZip();
    const cache = {};
    const promises = [];
      urlData.forEach((item) => {
        const promise = getFile(item).then((data) => {
          // 下载文件, 并存成ArrayBuffer对象
          const arr_name = item.split("/");
          const file_name = arr_name[arr_name.length - 1]; // 获取文件名
          zip.file(file_name, data, { binary: true }); // 逐个添加文件
          cache[file_name] = data;
        });
        promises.push(promise);
      });

      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then((content) => {
          // 生成二进制流
          FileSaver.saveAs(content, "种公猪二维码压缩文件.zip"); // 利用file-saver保存文件
        });
      });
    },
//以下写我们的请求方法并获取url地址数据
// 下载二维码
 downloadCode() {
      apiDownloadORCode({ pigArchivesIds: this.multipleSelection })
        .then((res) => {
         // 获取url数据集合
          console.warn( res.data.codeUrl)//["图片链接1","图片链接2"]
          var urlData = res.data.codeUrl;
         // 将url集合放入方法中获取zip格式文件
          this.filesToRar(urlData);
        })
        .catch((err) => {
          console.log(err);
          this.msgError("请求失败请重试");
        })
        .finally(() => {
          this.multipleSelection = [];
          this.getPigList();
        });
    },
</script>

参考文档链接: link.
将批量下载的图片打包成一个zip压缩文件的主要实现方法已贴出,有更有建议可在评论区留下宝贵的建议
注:在filesToRar方法里面的参数是数组格式,如果你的需求是将一张图片进行打包压缩的话,可在filesToRar方法内部对参数urlData进行处理,只可在方法内部做两步处理即可

let urlDatas = [urlData];
urlDatas.forEach(item=>{
......
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是代码实现前端代码: ```vue <template> <div> <button @click="downloadFile">下载文件</button> </div> </template> <script> export default { methods: { downloadFile() { window.open("/statics.zip"); }, }, }; </script> ``` 后端代码: ```java package com.example.demo.controller; import org.springframework.boot.configurationprocessor.json.JSONException; import org.springframework.boot.configurationprocessor.json.JSONObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @Controller public class FileDownloadController { @GetMapping("/download/statics") @ResponseBody public ResponseEntity<byte[]> downloadStaticResources() throws IOException { FileSystemResource fileSystemResource = new FileSystemResource(compressStaticResources()); byte[] fileBytes = new byte[(int) fileSystemResource.getFile().length()]; FileInputStream inputStream = new FileInputStream(fileSystemResource.getFile()); inputStream.read(fileBytes); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", "statics.zip"); headers.setContentLength(fileBytes.length); return ResponseEntity.ok().headers(headers).body(fileBytes); } private String compressStaticResources() { String tempZipPath = System.getProperty("java.io.tmpdir")+"/statics.zip"; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempZipPath))) { for (String staticsFolder : new String[]{"static", "public"}) { try { addFolderToZip(new ClassPathResource(staticsFolder).getFile(), staticsFolder, zos); } catch (IOException e) { e.printStackTrace(); } } return tempZipPath; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } private void addFolderToZip(File folder, String parentFolderName, ZipOutputStream zipOutputStream) throws IOException { if (folder.isDirectory()) { for (File file : folder.listFiles()) { addFolderToZip(file, parentFolderName, zipOutputStream); } } else { String name = folder.getName(); String path = folder.getPath().replace("\\", "/"); zipOutputStream.putNextEntry(new ZipEntry(path.substring(path.indexOf(parentFolderName), path.length()))); FileInputStream fileInputStream = new FileInputStream(folder); byte[] bytes = new byte[1024]; int length; while ((length = fileInputStream.read(bytes)) >= 0) { zipOutputStream.write(bytes, 0, length); } fileInputStream.close(); } } } ``` 这段代码使用了ZipOutputStream,将指定的静态资源文件夹进行了压缩,并通过@RepositoryRestController注解的Controller接口提供了下载静态资源文件的功能。 你可以在前端页面点击下载文件按钮,将会自动下载静态资源文件。同时,该代码也适用于任意SpringBoot+Vue项目。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值