批量下载图片打包zip
import downloadZipImage from '@/utils/downloadZipImage'
//勾选列表
selectValHandle(val) {
this.urlList = [];
this.urlList = val
},
//点击下载
if (this.urlList.length > 0) {
// 批量下载图片
downloadZipImage.downloadZipImage(this.urlList, 'img_url', 'imgName');
} else {
this.$message.error("请先勾选列表");
}
在utils/downloadZipImage封装下载图片组件
下包npm install file-saver jszip --save
//批量下载二维码
import FileSaver from "file-saver";
import JSZip from "jszip";
/**
* 下载压缩图片
* @param {any[]} imgArr 图片合集
* @param {string} imgKey 如果不是单纯的图片路径 需要传入路径的key
*/
function downloadZipImage(imgArr, imgKey = '', downloadName = 'img') {
if (!imgArr || !imgArr.length) {
return;
}
const zip = new JSZip();
// 创建images文件夹
const imgFolder = zip.folder('images');
let index = 0; // 判断加载了几张图片的标识
for (let i = 0; i < imgArr.length; i++) {
const itemImg = imgKey ? imgArr[i][imgKey] : imgArr[i];
/**
* 如果是Base64就不需要再做异步处理了
*/
const Base64Img = getBase64(itemImg);
if (Base64Img['then']) {
Base64Img['then'](function (base64) {
setBase64Img(zip, imgFolder, base64imgArr,index,downloadName);
index++;
}, function (err) {
console.log(err); //打印异常信息
});
} else {
setBase64Img(zip, imgFolder, Base64Img,imgArr,index,downloadName);
index++;
}
}
}
/**
* 将图片转换成base64 并返回路径
* @param img
* @param {number} width 调用时传入具体像素值,控制大小 ,不传则默认图像大小
* @param {number} height
* @returns {string}
*/
function getBase64Image(img, width = 0, height = 0) {
const canvas = document.createElement('canvas');
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL();
return dataURL;
}
/**
* 检查是不是Base64
* @param img
* @returns {boolean}
*/
function IsBase64(img) {
// jpg jpeg png gif
const _img = img.toLowerCase();
if (_img.endsWith('jpg') || _img.endsWith('jpeg') || _img.endsWith('png') || _img.endsWith('gif'))
return false;
return true;
}
/**
* 加载图片 加载成功后经图片返回
* @param img
* @returns {Promise<any>}
*/
function getBase64(img) {
let url = '';
if (IsBase64(img)) {
// 有一些数据 后台没有返回前缀
const _base64 = 'data:image/png;base64,';
if (img.startsWith(_base64)) {
url = img;
} else {
url = _base64 + img;
}
return url;
} else {
url = img;
const image = new Image();
image.crossOrigin = '*';
image.src = url;
return new Promise(function (resolve, reject) {
console.log(reject);
image.onload = function () {
resolve(getBase64Image(image)); //将base64传给done上传处理
}
});
}
}
/**
* 压缩图片
*/
function setBase64Img(zip, imgFolder, base64, imgArr, index, downloadName) {
base64 = base64.split('base64,')[1];
imgFolder.file(downloadName + '_' + index + '.png', base64, {
base64: true
});
if (index === imgArr.length - 1) {
zip.generateAsync({
type: 'blob'
}).then((blob) => {
FileSaver(blob, downloadName + '.zip');
// getZipFiles(blob)
});
}
}
export default {
downloadZipImage
}