前端利用oss图片地址返回url下载zip包

// 首先引入插件
npm install jszip

// 导入项目

import JSZip from 'jszip'

//
利用canvas.toDataURL 转换base64方法下载图片 downZip() {
    // 测试数据 let downLoadImageList
= ['https://img1.baidu.com/it/u=1112636550,1561836273&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1669568400&t=a9198393d4bafd6434583994737ec992', 'https://img1.baidu.com/it/u=1112636550,1561836273&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1669568400&t=a9198393d4bafd6434583994737ec992']; if ( downLoadImageList.length === 0 ) { this.$message({ type: 'warning', message: '请选中所要下载的图片' }); return } let zip = new JSZip(); let zipTitle = "订单"+ this.info.infoVo.orderNo let baseList = []; // 要下载图片的url for (let i = 0; i < downLoadImageList.length; i++) { let image = new Image(); // 解决跨域 Canvas 污染问题 crossOrigin,后端也要配置 image.setAttribute("crossOrigin", "anonymous"); let that = this; 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 base64Img = canvas.toDataURL(); // 转换成base64 数据 canvas.toDataURL("image/png"); baseList.push(base64Img.substring(22)); // 去掉base64编码前的 data:image/png;base64, 或者 base64Img.replace(/^data:image\/(png|jpg);base64,/, "") if (baseList.length === downLoadImageList.length && baseList.length > 0) { for (let k = 0; k < baseList.length; k++) { zip.file(`图片${Number(k) + 1}.png`, baseList[k], { base64: true }); } zip.generateAsync({ type: "blob" }).then(function (content) { FileSaver.saveAs(content, zipTitle + ".zip"); }); } that.$nextTick(()=>{ console.log('销毁', i) context.clearRect(0, 0, canvas.width, canvas.height); }) }; image.src = downLoadImageList[i]; } }

最终的到的就是一个zip包

 

关于阿里云跨域,oss配置如下图:

 

posted @ 2023-10-31 09:32  呼啦啦呜啦啦  阅读(194)  评论(0编辑  收藏  举报