1.首先引入或者npm下载fileSaver.js和jszip.min.js
2.我这里下载的内容是图片
<el-button type="primary" plain @click="onDownLoad(row)">下载</el-button>
// reconciliation:[{url:'https:xxxxx', type:'png', name:'xxxxx'}] 我这边后端返回的数据格式,不同格式稍微改一下循环和name
onDownLoad(row) {
if (row.reconciliation.length < 1) {
this.$message.warning("无可下载附件");
} else {
const pros = [];
row.reconciliation.forEach((item) => {
// 如果图片在别的服务器中,我们需要处理一下跨域问题,首先在vue.config.js中配置一下图
// 片下载的代理。
/* devServer: {
* proxy: {
* '/uploads': {
* target: 'https://xxx图片服务器地址.com',
* changeOrigin: true,
* pathRewrite: {
* '^/uploads': '' // 去掉路径中的 /uploads 前缀
* },
* secure: false,
* },
* }
},*/
// const path = item.split('https://图片服务器域名.com')[1] 我这边后端给的是全
// 路径,需要分割一下。
// const pro = this.getFile('/uploads' + path) // 使用代理路径
const pro = this.getFile(item.url);
pros.push(pro);
});
Promise.all(pros)
.then((blobs) => {
const files = row.reconciliation.map((item, index) => {
return {
name: `${Date.now().toString(16)}${index}.${item.type}`,
blob: blobs[index],
};
});
return files;
})
.then((files) => {
return this.createZIP(files);
})
.then((content) => {
saveAs(content, `${row.billNo}.zip`);
});
}
},
getFile(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((resp) => resp.blob())
.then(resolve, reject);
});
},
createZIP(files) {
return new Promise((resolve, reject) => {
const zip = new JSZip();
for (const f of files) {
zip.file(f.name, f.blob);
}
zip.generateAsync({ type: "blob" }).then(resolve, reject);
});
},
这里主要主要一下图片跨域的问题,需要前端处理跨域的话,就去配一下图片下载的代理服务器就可以了。下载别的类型附件,我没有试过,不过应该都可以用,不愿意试了,有需求再写吧😄