"file-saver": "^2.0.5",
"jszip": "^3.6.0"
import FileSaver from 'file-saver';
import JSZip from 'jszip';
export default class exportUtils {
static downloadZipByImageUrlMap(source, zipName) {
console.log('开始打包');
let doneCache = new Map();
let zip = new JSZip();
for (let dirName of source.keys()) {
let fileList = source.get(dirName);
let base64List = [];
doneCache.set(dirName, base64List);
for (let file of fileList) {
let image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function () {
let canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
let url = canvas.toDataURL();
canvas.toDataURL('image/png');
base64List.push({
name: file.name,
base64: url.substring(url.indexOf(',') + 1)
});
let ready = true;
for (let key of source.keys()) {
if (doneCache.get(key) === undefined || doneCache.get(key).length < source.get(key).length) {
ready = false;
break;
}
}
if (ready) {
console.log('开始下载');
for (let key of doneCache.keys()) {
let imageList = doneCache.get(key);
let imgDir = zip.folder(key);
for (let k = 0; k < imageList.length; k++) {
if (imageList[k].base64 === null) {
continue;
}
imgDir.file(imageList[k].name + '_' + k + '.png', imageList[k].base64, {base64: true});
}
}
zip.generateAsync({type: 'blob'}).then(function (content) {
FileSaver.saveAs(content, zipName + new Date().getTime() + '.zip');
});
}
};
image.onerror = function () {
for (let dieName of source.keys()) {
let tmpBase64List = doneCache.get(dieName);
for (let file of source.get(dieName)) {
if (image.currentSrc === file.url) {
tmpBase64List.push(file);
}
}
doneCache.set(dieName, tmpBase64List);
}
};
image.src = file.url;
}
}
}
}
' 3. 参考https://blog.csdn.net/qq_42157868/article/details/107368156
https://blog.csdn.net/qq_43258252/article/details/85063970