js实现下载(文件流、文件链接)

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
});
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值