1. 版本
"file-saver": "^2.0.5",
"jszip": "^3.6.0"
2. 实现
import FileSaver from 'file-saver';
import JSZip from 'jszip';
export default class exportUtils {
/**
* 前端 打包下载图片
* @param {*} source Map
* 例如:
* {
* "测试导出1": [
* {
* "name": "图片名称1",
* "url": "http://123.jpg"
* }
* ],
* "测试导出2": [
* {
* "name": "图片名称2",
* "url": "http://456.jpg"
* }
* ]
* }
*
* @param {*} zipName 文件名 如: '压缩文件' 不需要加扩展名(.zip)
* */
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 = [];
// 缓存已经加载完成的图片base64
doneCache.set(dirName, base64List);
for (let file of fileList) {
let image = new Image();
// 解决跨域 Canvas 污染问题
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);
// 得到图片的base64编码数据
let url = canvas.toDataURL();
canvas.toDataURL('image/png');
// 去掉base64编码前的 data:image/png;base64,
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.youkuaiyun.com/qq_42157868/article/details/107368156
https://blog.youkuaiyun.com/qq_43258252/article/details/85063970