vue的axios攜帶token下載文件

1,統一在接口的請求頭裏攜帶token
在src的main.js裏寫入

//axios配置
axios.interceptors.request.use(
    config => {
        if (localStorage.getItem('token')) {
            config.headers.token = localStorage.getItem('token');
        }
        //get請求方式中   對數組進行統一處理  格式化數組
        // if (config.method === 'get') {
        //     config.paramsSerializer = function(params) {
        //         return qs.stringify(params, { arrayFormat: 'repeat' })
        //     }
        // }
        return config;
    },
    error => {
        return Promise.reject(error);
    });

2,發送請求

    //    導出區域能耗數據
        async get_daochu_data({commit},v){
            let res = await axios.get('xxxxxxxxx接口地址xxxxxxx',{
                params:{
                    dateType: v.dateType,
                    userId: v.userId,
                    buildingId: v.buildingId,
                    parentId:v.parentId,
                    roomId: v.roomId,
                    beginTime: v.beginTime,
                    endTime: v.endTime
                },
                responseType: 'blob'
            })

            if(res.status == 200){
                commit('SET_DAOCHU_DATA',res.data)
            }
        }

其中 **responseType: ‘blob’**非常關鍵,這將讓你接收的數據以文件流的方式存儲
3,設置按鈕(點擊按鈕即可下載)
頁面代碼

<div class="table-button">
      <el-button type="primary" @click="getDaochu">導出</el-button>
</div>

script代碼

getDaochu(){
                this.get_daochu_data({
                    // 區域:
                    buildingId: this.buildingId,
                    beginTime: this.month,
                    parentId: this.pid,
                    dateType: this.chooseGroupValue,
                }).then(()=>{
                    let url = window.URL.createObjectURL(new Blob([this.daochu_data]));
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    link.setAttribute("download",  "區域能耗.xls");

                    document.body.appendChild(link);

                    link.click();
                })
            }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章