先引用jquery、jszip、FileSaver,然后封装下载方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
一、引用 <script src="lib/jquery-3.4.0.min.js"></script> <script src="lib/jszip.min.js"></script> <script src="lib/FileSaver.min.js"></script> 二、方法封装 var FunLib = { // 图片打包下载 download: function (images) { FunLib.packageImages(images) }, // 打包压缩图片 packageImages: function (imgs) { var imgBase64 = [] var imageSuffix = [] // 图片后缀 var zip = new JSZip() var img = zip.folder("images") for (var i = 0; i < imgs.length; i++) { var src = imgs[i].url var suffix = src.substring(src.lastIndexOf(".")) imageSuffix.push(suffix) FunLib.getBase64(imgs[i].url).then(function (base64) { imgBase64.push(base64.substring(22)) if (imgs.length === imgBase64.length) { for (var i = 0; i < imgs.length; i++) { img.file(imgs[i].name + imageSuffix[i], imgBase64[i], {base64: true}) } zip.generateAsync({type: "blob"}).then(function (content) { saveAs(content, "images.zip") }) } }, function (err) { console.log(err) }) } }, // 传入图片路径,返回base64 getBase64: function (img) { var image = new Image() image.crossOrigin = 'Anonymous' image.src = img var deferred = $.Deferred() if (img) { image.onload = function () { var canvas = document.createElement("canvas") canvas.width = image.width canvas.height = image.height var ctx = canvas.getContext("2d") ctx.drawImage(image, 0, 0, canvas.width, canvas.height) var dataURL = canvas.toDataURL() deferred.resolve(dataURL) } return deferred.promise() } } } 三、方法调用 FunLib.download([{url:'imageUrl1',name:'图片1'},{url:'imageUrl2',name:'图片2'})] |