vue+axios下载后台返回的文件流

//拦截器
axios.interceptors.response.use(response => {//数据拿到之后
    NProgress.done()
    if(response.headers['content-disposition']){//此判断主要是要取到content-disposition的值
        return response
    }else{
        return response.data
    }
}, error => {
    Message.error('访问异常,稍等刷新重试');
    return Promise.reject(error.response);
});

//http请求
postBlob(url){
    return axios({
        method: "post",
        baseURL: localhosts,
        url,
        headers: {
            // 在请求头里面加个  Authorization
            Authorization: sessionStorage.getItem('token'),
            "X-Auth-Token": sessionStorage.getItem('xAuthToken')
        },
        responseType:"blob"
    })
    .then(res => {
        return res;
    },
    err => {
        Message.error('导出失败');
        return err;
    });
},

//调用
download(){
    //this.api.downloadOrder为接口地址
    this.http.postBlob(this.api.downloadOrder)
    .then(res => {
        if(res){
            var fileName = decodeURI(res.headers['content-disposition'].split('=')[1]);
            var blob = new Blob([res.data]);
            if(window.navigator.msSaveOrOpenBlob){
                navigator.msSaveBlob(blob,fileName);
            }else{
                var a = document.createElement("a");
                a.download = fileName;
                a.href = window.URL.createObjectURL(blob);
                a.click();
            }
        }
    })
},

 

你可能感兴趣的:(vue+axios下载后台返回的文件流)