1、首先安装node_module插件
npm i jszip file-saver
2、导入插件
import { saveAs } from ‘file-saver’;
import JSZip from ‘jszip’
3、代码实现
created(){
let arr = [{picName:‘图片名字’,picUrl:‘https://gimg2.baidu.com/image_search/src=http%3A%2F%2Farticle-fd.zol-img.com.cn%2Ft_s998x562c5%2Fg5%2FM00%2F0A%2F02%2FChMkJltpVKGIQENcAAKaC93UFtUAAqi5QPdcOwAApoj403.jpg&refer=http%3A%2F%2Farticle-fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639737146&t=96efdde36bc7cd05972cad237e23dae6’}]
this.zip(arr)
},
methods:{
zip (arr) {
var zip = new JSZip();
// 创建images文件夹
var imgFolder = zip.folder(“images”);
let flag = 0 // 判断加载了几张图片的标识
for (let i = 0;i < arr.length;i++) { //遍历数组arr
this.getBase64(arr[i].picUrl).then(base64=>{ //调用getBase64()方法,传入图片网络地址得到base64数据
base64 = base64.split('base64,')[1]
imgFolder.file(arr[i].picName+ '.png', base64, { base64: true })//自定义图片名字,存进images文件夹里面
if (flag === arr.length - 1) {
zip.generateAsync({ type: "blob" }).then((blob) => {
saveAs(blob, "压缩包名字.zip")//自定义文件压缩包名字
})
}
flag++
});
}
},
//传入图片地址,返回base64格式数据
getBase64(img){
var image = new Image();
image.crossOrigin = ‘*’;//解决图片跨域问题
image.src = img;
return new Promise((resolve,reject)=>{
image.onload = ()=>{
resolve(this.getBase64Image(image));
}
})
},
//创建画布,将图片渲染到画布上,再将画布转为base64格式数据返回出来
getBase64Image(img,width,height) {
var canvas = document.createElement(“canvas”);
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
var ctx = canvas.getContext(“2d”);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL();
return dataURL;
},
}