vue批量下载图片打包为压缩包

yarn add jszip
yarn add file-saver
<template>
  <div class="home">
    <button @click="attachDownload">批量下载</button>
    <div class="home_wrap">
      <div class="home_wrap_item" v-for="item in imageList" :key="item.url">
        <input v-model="item.is_checkbox" type="checkbox" id="c1" name="cc" />
        <label for="c1"><span></span></label>
        <img :src="item.url" alt="" />
      </div>
    </div>
  </div>
</template>

<script>
import JSZip from "jszip";
import FileSaver from "file-saver";
export default {
  data() {
    return {
      imageList: [
        {
          url: "https:\/\/pic.rmb.bdstatic.com\/bjh\/7ab6977e3304d6bd72704cc434fe52d3.jpeg",
          id: "111",
          is_checkbox:false,
        },
        {
          url: "https:\/\/fc.sinaimg.cn\/large\/419f07d1gy1hg5xdr2f1aj21kw2cmx6s.jpg",
          id: "222",
          is_checkbox:false,
        },
        {
          url: "https:\/\/img10.360buyimg.com\/ddimg\/jfs\/t1\/132974\/31\/29586\/3214914\/633016ccEb4f7672a\/b05ac0be612c7519.jpg",
          id: "333",
          is_checkbox:false,
        },
        {
          url: "https:\/\/pic.rmb.bdstatic.com\/bjh\/4363032f4ed4400e3b608584fa2664a7.jpeg",
          id: "444",
          is_checkbox:false,
        },
      ],
    };
  },
  methods: {
    async attachDownload() {
      const arr = this.imageList.filter(ele=>ele.is_checkbox==true)
      const zip = new JSZip();
      const cache = {};
      const downloadPromises = arr.map(async (item) => {
        try {
          if (item.url) {
            const data = await this.getImgArrayBuffer(item.url);
            zip.file(item.id + ".png", data, { binary: true });
            cache[item.id] = data;
          } else {
            throw new Error(`图片${item.fileName}地址错误,下载失败`);
          }
        } catch (error) {
          console.error("文件获取失败", error);
        }
      });
      try {
        await Promise.all(downloadPromises);
        const content = await zip.generateAsync({ type: "blob" });
        FileSaver.saveAs(content, "病例编辑图片");
      } catch (error) {
        console.error("文件压缩失败", error);
      }
    },
    async getImgArrayBuffer(url) {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }
      return await response.blob();
    },
  },
};
</script>
<style lang="scss">
.home {
    width: 100vw;
    height: 100vh;
  &_wrap {
    display: flex;
    flex-wrap: wrap;
    &_item {
      width: 200px;
      height: 200px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>

你可能感兴趣的:(vue.js,javascript,前端)