场景:批量导出图片并放在一个zip文件下导出,借助jszip以及file-saver插件
1、npm install jszip / npm install file-saver
import JSZip from 'jszip';
import FileSaver from 'file-saver';
/**
* @description:图片导出zip文件
* @param {*} title zip文件名
* @param {*} imgList 需要导出的图片列表
* @param {*} eachImgKey 每张图片名称的key值 默认为name
* @param {*} eachUrlKey 每张图片名称的url值 默认为baseImg
* @return {*}
*/
getImageZip(title, imgList, eachImgKey = 'name', eachUrlKey = 'baseImg') {
let zip = new JSZip();
let imgs = zip.folder(title);
let baseList = [];
imgList.forEach(imgD => {
let name = imgD[eachImgKey]; //每张图片的名称
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);
let url = canvas.toDataURL(); // 得到图片的base64编码数据
canvas.toDataURL('image/png');
baseList.push({ name, img: url.substring(22) });
if (baseList.length === imgList.length) {
if (baseList.length > 0) {
baseList.forEach(baseImg => {
imgs.file(baseImg.name + '.png', baseImg.img, {
base64: true,
});
});
zip.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, title + '.zip');
});
}
}
};
image.src = imgD[eachUrlKey] = `${imgD[eachUrlKey]}`;
});
},
2、使用封装的方法:
<a @click="getImageZip('susu测试', img_list)">导出</a>
let img_list =[
{
name: '图片一',
baseImg: 'https://res.miaocode.com/web/mk/csys/bg3_new.png',
},
{
name: '图片二',
baseImg: 'https://res.miaocode.com/web/mk/csys/bg3_new.png',
},
]
效果: