工具:
import JSZip from "jszip";
import FileSaver from "file-saver";
实现:
第一步:获取图片url,目前只遇到过两种情况:
- 通过dom获取,例如 卡片+多选按钮组 方式的展示形式,勾选导出,此时可根据dom获取url;
- 通过接口获取
downLoad(amount) { let url2 = ''; // 照片 let self = this; Axios.get(url2) .then((res) => { let arr = []; for (let i = 0, len1 = res.data.data.length; i < len1; i++) { if (res.data.data[i].pictureUrl !== '') { arr.push(res.data.data[i]) } } let result = []; for (let i = 0, len2 = arr.length; i < len2; i += 20) { result.push(arr.slice(i, i + 20)); } self.packageImages(result) }) .catch((err) => { console.log(err); }) }
总之能拿到有效url即可
第二步:判断图片地址是否有效
async validateImage(pathImg) { // 验证图片地址是否有效 var ImgObj = new Image(); ImgObj.src = pathImg; return ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0); }
注:要考虑到会有空的情况,应该确定已有照片被选中且图片地址有效,无效地址(包括空)应过滤掉
第三步:图片转base64
getBase64(img) { function getBase64Image(img, width, height) { // width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小 let canvas = document.createElement("canvas"); canvas.width = width || img.width; canvas.height = height || img.height; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); let dataURL = canvas.toDataURL(); return dataURL; } let image = new Image(); image.crossOrigin = 'Anonymous'; image.src = img; let deferred = $.Deferred(); if (img) { image.onload = function () { deferred.resolve(getBase64Image(image)); }; return deferred.promise(); } }
第四步:打包下载,这里是每20张图片分一个目录,如果不需要分目录就不用将得到的图片拆成二维数组,直接打包就好
packageImages(arr, index) { let self = this; let imgs = []; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { if (!arr[i][j].pictureUrl.match('base64,')) { imgs.push(arr[i][j]); } } } let imgBase64 = []; let imgsName = []; let imageSuffix = [];// 图片后缀 let zip = new JSZip(); for (let j = 0; j < imgs.length; j++) { let suffix = ".jpg"; imageSuffix.push(suffix); this.getBase64(imgs[j].pictureUrl) .then(function (base64) { imgBase64.push(base64.substring(22)); let fileName = imgs[j].cardId; imgsName.push(fileName); }, function (err) { console.log(err); }); } function tt() { setTimeout(function () { if (imgs.length === imgBase64.length) { for (let i = 0; i < arr.length; i++) { let begin = i * 20 + 1; let end = 0; if (arr[i].length < 20) { end = imgsName.length; } else { end = (i + 1) * 20 } let img = zip.folder("photos" + begin + "-" + end); for (let j = 0; j < arr[i].length; j++) { img.file(imgsName[i * 20 + j].trim() + imageSuffix[i * 20 + j], imgBase64[i * 20 + j], {base64: true}); } } zip.generateAsync({type: "blob"}).then(function(content) { FileSaver.saveAs(content, "images.zip"); }); } else { tt(); } }, 100); } tt(); }
数据太多应该给出进度条,分目录下载也可以分成多个zip下载,每20个下载一下