vue实现使用JSZip批量下载图片
1 import JSZip from "jszip"; 2 import { saveAs } from 'file-saver'; 3 import $ from 'jquery' 4 5 // jszip打包下载图片 6 function saveImgZip(imgUrlArrs,typeTxt) { 7 var imgUrlArr = []; // 图片列表 8 imgUrlArr = imgUrlArrs 9 var imgBase64 = {};//存放转成base64的图片,采用键值对形式就行存储,不采用数组。因为数组在异步中会导致存取数据的无序,数据混乱 10 var imgNameArr = []; // 图片名称 11 var imageSuffix = []; // 图片后缀 12 for (var i = 0; i < imgUrlArrs.length; i++) { 13 let imgurl = decodeURIComponent(imgUrlArrs[i]) 14 // 图片后缀 15 var suffix = imgurl.substring(imgurl.lastIndexOf(".")); 16 imageSuffix.push(suffix); 17 //获取文件的名称 18 var startIndex = imgurl.lastIndexOf("/"); 19 var endIndex = imgurl.lastIndexOf("."); 20 var fileName = imgurl.substring(startIndex + 1, endIndex); 21 console.log(fileName); 22 imgNameArr.push(fileName); 23 } 24 // 创建JSZip对象 25 var zip = new JSZip(); 26 // 创建文件夹 27 var img = zip.folder("images"); 28 // 读取图片返回base64 29 for (var i = 0; i < imgUrlArr.length; i++) { 30 getBase64(imgUrlArr[i],i).then(function (base64,index) { 31 imgBase64[index] = base64.substring(22); 32 }, function (err) { 33 console.log(err); 34 }); 35 } 36 function downloadZip() { 37 setTimeout(function () { 38 if (imgUrlArr.length == Object.keys(imgBase64).length) { 39 for (var i = 0; i < imgUrlArr.length; i++) { 40 img.file(imgNameArr[i] + imageSuffix[i], imgBase64[i], { base64: true }); 41 } 42 let zipfilename = `文件名批量下载_${Date.now()}.zip` 43 zip.generateAsync({ type: "blob" }).then(function (content) { 44 saveAs(content, zipfilename) 45 }); 46 } else { 47 downloadZip(); 48 } 49 }, 100); 50 } 51 downloadZip(); 52 } 53 54 //图片转base64; 传入图片路径,返回base64 55 function getBase64(img,index) { 56 function getBase64Image(img, width, height) { 57 var canvas = document.createElement("canvas"); 58 canvas.width = width ? width : img.width; 59 canvas.height = height ? height : img.height; 60 var ctx = canvas.getContext("2d"); 61 ctx.drawImage(img, 0, 0, canvas.width, canvas.height); 62 var dataURL = canvas.toDataURL(); 63 return dataURL; 64 } 65 66 var image = new Image(); 67 image.crossOrigin = 'Anonymous'; 68 image.src = img; 69 /* 70 * deferred对象是一个延迟对象,意思是函数延迟到某个点才开始执行,改变执行状态的方法有两个(成功:resolve和失败:reject), 71 * 分别对应两种执行回调(成功回调函数:done和失败回调函数fail) 72 * */ 73 var deferred = $.Deferred(); 74 if (img) { 75 image.onload = function () { 76 // 执行成功回调 77 deferred.resolve(getBase64Image(image),index); 78 } 79 return deferred.promise(); 80 } 81 } 82 export { 83 saveImgZip 84 }
引入包
npm install jszip
npm install file-saver
然后直接将上面的代码复制到js就行
调用方法
saveImgZip(imglist,'共享图库')
imglist是图片地址集合