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

发布时间:2024年01月16日
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>

文章来源:https://blog.csdn.net/sjajjajusja/article/details/135631109
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。