1.可直接下载的文件链接
js
const fileDownloadUrl = '';
window.open(fileDownloadUrl)
// 或者
location.href = fileDownloadUrl
// 或者js实现一个a链接
fetch(fileDownloadUrl).then(res => res.blob()).then(blob => {
const a = document.createElement('a');
document.body.appendChild(a)
a.style.display = 'none'
// 使用获取到的blob对象创建的url
const url = window.URL.createObjectURL(blob);
a.href = url;
// 指定下载的文件名
a.download = name;
a.click();
document.body.removeChild(a)
// 移除blob对象的url
window.URL.revokeObjectURL(url);
});
vue
<!-- element组件 -->
<el-link type="primary" :underline="false" :href="fileDownloadUrl">模板下载</el-link>
<!-- 用a链接 -->
<a :href="fileDownloadUrl" :download="fileDownloadUrl" target="_blank">
2.文件流
axios版
const apiurl = '' // 接口地址
this.exportLoading = true
axios.post(apiurl, params, {
'responseType': 'blob' //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置!!!
}).then( (response) =>{
console.log('response', response, response.data.size)
this.exportLoading = false
if(response.data){
if(response.data.size < 1000){
// 根据文件流的大小判断异常情况
if(response.data.size == 63){
this.$message.warning('查无结果');
return
}
if(response.data.size == 84){
this.$message.warning('导出数据超出最大限制值');
return
}
}else{
const blob = new Blob([response.data],{type: 'application/vnd.ms-excel'})
const linkNode = document.createElement('a');
linkNode.style.display = 'none';
linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
document.body.appendChild(linkNode);
linkNode.click(); //模拟在按钮上的一次鼠标单击
URL.revokeObjectURL(linkNode.href); // 释放URL 对象
document.body.removeChild(linkNode);
}
}
}).catch( (error) =>{
console.log(error);
this.exportLoading = false
});
版权声明:本文为qq_32886245原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。