使用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
});

type:application/vnd.ms-excel
是以excel文件下载。
若改成application/zip则是以zip压缩包方式下载,具体什么文件要根根据后台接口地址而定。

猜你喜欢

转载自blog.csdn.net/qq_44732146/article/details/129150097
今日推荐