头部引入文件
import JSZip from "jszip";
import FileSaver from "file-saver";
import AdminApi from "@/api/export";
//res.data 接口获取到的数据
if (res.data.length == 1) {
//单个下载图片第一种 let data = `${this.$moment(new Date()).format('YYYY-MM-DD')}` //下载文件名字以时间命名 var image = new Image(); // 解决跨域 Canvas 污染问题 image.setAttribute("crossOrigin", "anonymous"); image.onload = function () { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据 var a = document.createElement("a"); // 生成一个a元素 var event = new MouseEvent("click"); // 创建一个单击事件 a.download = data + '_1' || "photo"; // 设置图片名称 a.href = url; // 将生成的URL设置为a.href属性 a.dispatchEvent(event); // 触发a的单击事件 };
//单个图片下载路径 image.src = res.data[0].filePath;
} else {//多个文件夹里面包含图片 let blogTitle = "电子发票"; //文件夹名 let zip = new JSZip(); let imgs = zip.folder(blogTitle); let baseList = [];
//下载的数据及格式整理 let arr = res.data; let exportImg = arr.map((item, index) => {//数组对象 return { name: `${this.$moment(new Date()).format('YYYY-MM-DD')}_${index + 1}`, //文件名字 images: item.filePath,//文件链接 }; }) this.imgLoading = false; for (let i = 0; i < exportImg.length; i++) { let image = new Image(); // 解决跨域 Canvas 污染问题 image.setAttribute("crossOrigin", "anonymous"); image.onload = function () { let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; let context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); let url = canvas.toDataURL(); // 得到图片的base64编码数据 canvas.toDataURL("image/png"); baseList.push(url.substring(22)); // 去掉base64编码前的 data:image/png;base64, if (baseList.length === exportImg.length && baseList.length > 0) { for (let k = 0; k < baseList.length; k++) { imgs.file(exportImg[k].name + ".png", baseList[k], { base64: true, }); } zip.generateAsync({ type: "blob" }).then(function (content) { FileSaver.saveAs(content, blogTitle + ".zip"); // see FileSaver.js }); } }; image.src = exportImg[i].images; } }