一、安装JSZip
npm install jszip
how to use JSZip:链接: https://stuk.github.io/jszip/documentation/examples.html.
二、实现代码
由于JSZip只接受二进制文件流,需要转换为base64图片。
//使用canvas.toDataURL获取base64
function getBase64Image(img) {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
let dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
};
//初始化zip, 创建pic文件夹
let zip = new JSZip();
let img = zip.folder("pic");
//图片加载完成后进行的操作,多个图片可以在外面加循环
let imgUrl = require('imagUrl');
let image = new Image();
image.src = imgUrl;
image.onload = function() {
//console.log(getBase64Image(image))
let base64Img = getBase64Image(image).split(',')[1];
img.file('test.jpg', base64Img, {base64: true});
zip.generateAsync({ type: "blob" })
.then(function (content) {
saveAs(content, "example.zip");
});
};