单张图片下载
handleAlipayQrCode(id,name){
// 请求后端接口返回url
addAlipayQrCode(id).then(response=>{
this.downloadByBlob(response.data.url,name);
});
},
downloadByBlob(url,name) {
let image = new Image()
image.setAttribute('crossOrigin', 'anonymous')
image.src = url
image.onload = () => {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
canvas.toBlob((blob) => {
let url = URL.createObjectURL(blob)
this.download(url,name)
// 用完释放URL对象
URL.revokeObjectURL(url)
})
}
},
download(href, name) {
let eleLink = document.createElement('a')
eleLink.download = name
eleLink.href = href
eleLink.click()
eleLink.remove()
},
图片打包下载
打开命令行,执行以下命令
npm i jszip
npm i file-saver
在对应的页面加上以下代码
import FileSaver from 'file-saver';
import JSZip from 'jszip';
let imgList =[
{
name: '图片一',
baseImg: 'https://res.miaocode.com/web/mk/csys/bg3_new.png',
},
{
name: '图片二',
baseImg: 'https://res.miaocode.com/web/mk/csys/bg3_new.png',
},
]
批量导出方法
exportImg() {
this.getImageZip('科室二维码', this.imgList);
},
getImageZip(title, imgList, eachImgKey = 'name', eachUrlKey = 'baseImg') {
let zip = new JSZip();
let imgs = zip.folder(title);
let baseList = [];
imgList.forEach(imgD => {
let name = imgD[eachImgKey]; //每张图片的名称
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({ name, img: url.substring(22) });
if (baseList.length === imgList.length) {
if (baseList.length > 0) {
baseList.forEach(baseImg => {
imgs.file(baseImg.name + '.png', baseImg.img, {
base64: true
});
});
zip.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, title + '.zip');
});
}
}
};
image.src = imgD[eachUrlKey] = `${imgD[eachUrlKey]}`;
});
},