Vue 打包下载图片
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(); }); },
相关推荐
hygbuaa 2020-11-22
坚持着执着 2020-07-16
zhaolisha 2020-06-16
坚持着执着 2020-06-14
李永毅 2020-05-29
malachuan 2020-05-17
Richardxx 2020-05-16
87510793 2020-05-09
用不完的好奇心 2020-05-08
hygbuaa 2020-02-20
zhaolisha 2020-01-12
wanghongsha 2019-12-15
83447400 2019-09-17
86520093 2019-11-18
89401052 2014-06-25
heimeiyingwang 2015-03-19