JSZIP打包下载图片

import moment from 'moment';
import JSZip from 'jszip';
import saveAs from 'jszip/vendor/FileSaver';

  const getFile = (url) => {
    return new Promise((resolve, reject) => {
      try {
        const image = new window.Image();
        image.crossOrigin = 'Anonymous';
        image.src = url;
        image.onload = () => {
          const canvas = document.createElement('canvas');
          canvas.width = image.width;
          canvas.height = image.height;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
          const dataURL = canvas.toDataURL();
          resolve(dataURL.substring(22));
        };
      } catch (err) {
        reject(err);
      }
    });
  };

  const batchDown = () => {
    const selectedList = [{id:1,picName:'http://127.0.0.1/1.jpg'},{id:2,picName:'http://58.33.264.241:9844/2.jpg'}];
    if (!selectedList || selectedList.length === 0) {
      console.log('请选择异常数据');
      return;
    }
    const zip = new JSZip();
    const promises = [];
    for (const item of selectedList) {
      const url = item.picName;
      const promise = getFile(url).then((data) => {
        zip.file(item.id + '.jpg', data, { base64: true });
      });
      promises.push(promise);
    }
    const zipName = moment().format('YYYY-MM-DD HH:mm:ss');
    Promise.all(promises)
      .then(() => {
        zip.generateAsync({ type: 'blob' }).then((content) => {
          // 生成二进制流
          saveAs(content, zipName); // 利用file-saver保存文件
        });
      })
      .catch((err) => {
        console.log('导出失败', err);
      });
  };

 

posted @ 2022-11-23 16:52  卓扬  阅读(262)  评论(0编辑  收藏  举报