1,安装依赖npm
//jszip是一个用于创建、读取和编辑.zip文件的JavaScript库
https://stuk.github.io/jszip/
npm install jszip
https://www.npmjs.com/package/file-saver
npm install file-saver
2,在所需的页面中引入对应包
import JSZip from "jszip";
import FileSaver from "file-saver";
3,执行打包方法
arrImages:[{fileUrl:'图片地址',renameFileName:'图片名'}] filename:'打包名'
this.filesToRar(arrImages, "相册");
filesToRar(arrImages, filename) {
let _this = this;
let zip = new JSZip();
let cache = {};
let promises = [];
let times = 1;
var setIme = setInterval(() => {
times++;
console.log(times);
}, 1000);
for (let item of arrImages) {
const promise = _this.getImgArrayBuffer(item.fileUrl).then(data => {
// 下载文件, 并存成ArrayBuffer对象(blob)
zip.file(item.renameFileName, data, { binary: true }); // 逐个添加文件
cache[item.renameFileName] = data;
});
promises.push(promise);
}
Promise.all(promises)
.then(() => {
zip.generateAsync({ type: "blob" }).then(content => {
// 生成二进制流
FileSaver.saveAs(content, filename); // 利用file-saver保存文件 自定义文件名
this.$notify.close();
this.$notify({
message: "压缩完成"
});
window.clearInterval(setIme);
});
})
.catch(res => {
this.$notify({
message: "文件压缩失败"
});
});
},
//获取文件blob
getImgArrayBuffer(url) {
let _this = this;
return new Promise((resolve, reject) => {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function() {
if (this.status == 200) {
resolve(this.response);
} else {
reject(this.status);
}
};
xmlhttp.send();
});
},
效果: