js实现下载(文件流式)方法详解与完整实例源码
作者:阿晏_
这篇文章主要介绍了js实现下载(文件流式)的方法,需要的朋友可以参考下
在介绍JS文件流式下载文件方法之前,先记录下window.location.href的使用方法
window.location.href的用法
javascript中的location.href有很多种用法,主要如下。
self.location.href="/url"//当前页面打开URL页面 location.href="/url"//当前页面打开URL页面 windows.location.href="/url" //当前页面打开URL页面,前面三个用法相同。 this.location.href="/url" //当前页面打开URL页面 parent.location.href="/url" // 在父页面打开新页面 top.location.href="/url" //在顶层页面打开新页面
如果页面中自定义了frame,那么可将parent self top换为自定义frame的名称,效果是在frame窗口打开url地址
此外,window.location.href=window.location.href;和window.location.Reload()和都是刷新当前页面。区别在于是否有提交数据。
当有提交数据时,window.location.Reload()会提示是否提交,window.location.href=window.location.href;则是向指定的url提交数据
JS文件流式下载文件源码实例
下面是使用axios写的一个完整JS文件流式下载文件的完整源码
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
});