我尝试了以下功能,但它只允许我下载 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);
})
}
答案 0 :(得分: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());
}
这将流式下载,从而最大限度地提高性能。