【问题标题】:How to zip images by its url from s3如何通过 s3 的 url 压缩图像
【发布时间】:2021-05-30 02:23:33
【问题描述】:

我尝试了以下功能,但它只允许我下载 1 张照片,
所以我正在寻找一种方法来压缩图像并下载它。

但是我在stackoverflow中搜索了很多帖子,找不到正确的方法。

function downloadPhotos() {
  let files = [{
    image: "abc.com/image/01"
  }, {
    image: "abc.com/image/02"
  }]
  files.map(file => {
    const link = document.createElement('a');
    link.href = file.image;
    link.setAttribute('download', `sample`)
    document.body.appendChild(link);
    link.click();
    link.parentNode.removeChild(link);
  })
}

【问题讨论】:

标签: javascript zip


【解决方案1】:

您需要一个 ZIP 存档生成库。您可以使用fflate 以流式方式快速执行此操作以节省内存。

import { Zip, ZipPassThrough } from 'fflate';
import streamSaver from 'streamsaver';

function downloadPhotos() {
  let files = [{
    image: "https://example.com/image1"
  }, {
    image: "https://example.com/image2"
  }];
  const zip = new Zip();
  const rs = new ReadableStream({
    start(controller) {
      zip.ondata = (err, dat, final) => {
        if (err) {
          controller.error(err);
        } else {
          controller.enqueue(dat);
          if (final) controller.close();
        }
      }
    }
  });
  rs.pipeTo(streamSaver.createWriteStream('example.zip'));
  return Promise.all(files.map(async meta => {
    const stream = (await fetch(meta.image)).body;
    const file = new ZipPassThrough(meta.image);
    zip.add(file);
    const reader = stream.getReader();
    while (true) {
      const { value, done } = await reader.read();
      if (done) {
        file.push(new Uint8Array(0), true);
        return;
      };
      file.push(value);
    }
  })).then(() => zip.end());
}

这将流式传输下载,从而最大限度地提高性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多