效果:
npm install jszip
npm install file-saver
import JSZip from "jszip";
import FileSaver from "file-saver";
BatchDownload(){
const fileName = '测试'
const FileName = '压缩包'
const fileType = 'jpg'
const url = this.getImgArrayBuffer('https://xxx.jpg')
let zip = new JSZip();
const img = zip.folder(FileName);
const meshes = img.folder('照片')
img.file(`${fileName}.` + 'xls', url, { base64: true });
// meshes.file(`mesh.` + fileType, url, { base64: true });
const imgDataUrl = [
{
nickname: '小王.jpg',
path: 'https://xxx.jpg'
},
{
nickname: '小羊.jpg',
path: 'https://xxx.jpg'
}
]
let _this = this;
let cache = {};
let promises = [];
_this.title = '正在加载压缩文件';
for (let item of imgDataUrl) {
const promise= _this.getImgArrayBuffer(item.path).then(data => {
// 下载文件, 并存成ArrayBuffer对象(blob)
meshes.file(item.nickname, data, { base64: true });
// zip.file(item.nickname, data, { binary: true }); // 逐个添加文件
cache[item.nickname] = data;
});
promises.push(promise);
}
Promise.all(promises).then(() => {
zip.generateAsync({ type: 'blob', compression: 'DEFLATE', compressionOptions: { level: 9 } }).then((content) => {
FileSaver.saveAs(content, `${FileName}.zip`);
});
})
},
//通过url 转为blob格式的数据
getImgArrayBuffer(url){
let _this=this;
return new Promise((resolve, reject) => {
//通过请求获取文件blob格式
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();
});
},
啦-啦-啦啦~ 啦-啦-啦-啦啦~ 完成啦~~~