fetch请求实现文件下载

6,697 阅读1分钟

项目需求是前台页面通过后台传输的数据流实现下载功能

使用fetch请求后台,起初写法如下:

downloadData=(excelUrl,reportName)=>{
    let token = "Bearer " + sessionStorage.getItem('token')
    fetch(DOWNLOAD + excelUrl, {
        headers: {
            'Content-type': 'application/json;charset=UTF-8',
            'Authorization': token
        }
    }).then(res => res.blob().then(blob => {
        var filename=`${reportName}.xls`
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(blob); 
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    }))
}

结果测试出现的情况是:在Google浏览器中测试成功,而在firefox中实现却没有反应,F12查看请求情况,发现请求和返回都没有问题。于是猜测是前端代码兼容性不行。最后的解决方案是:

downloadData=(excelUrl,reportName)=>{
    let token = "Bearer " + sessionStorage.getItem('token')
    fetch(DOWNLOAD + excelUrl, {
        headers: {
            'Content-type': 'application/json;charset=UTF-8',
            'Authorization': token
        }
    }).then(res => res.blob().then(blob => {
        var filename=`${reportName}.xls`
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, filename);  //兼容ie10
        } else {
            var a = document.createElement('a');
            document.body.appendChild(a) //兼容火狐,将a标签添加到body当中
            var url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
            a.href = url;
            a.download = filename;
            a.target='_blank'  // a标签增加target属性
            a.click();
            a.remove()  //移除a标签
            window.URL.revokeObjectURL(url);
        }
    }))
}

测试成功!