axios 請求並下載 blob 文件 並對後臺返回錯誤code進行攔截

1.axios 請求中添加

responseType: 'blob' 字段

例如
exportSettled(params) {
        const sendObj = {};
        ({
            shopCode: sendObj.shopCode,// 網點code
        } = params);
        return service({
            url: requestInterfaceList.exportSettled,
            method: 'get',
            responseType: 'blob', // 這裏添加響應類型 爲blob
            params: sendObj
        });
    }

  

 

2.創建一個a標籤進行下載

createDownload(blob, name) {
        let url = window.URL.createObjectURL(new Blob([blob]));
        const $a = document.createElement('a');
        $a.style.display = 'none';
        $a.href = url;
        $a.setAttribute('download', name);
        $a.click();
    }

  

3.爲防止 後臺返回錯誤的code無法攔截 所以需要將blob轉換爲json 解析

blobToText(blob) {
        return new Promise((resolve, reject) => {
            const fileReader = new FileReader();
            fileReader.readAsText(blob);
            fileReader.onload = function () {
                try{
                    const result = JSON.parse(this.result);
                    if(result && result['resultCode'] === 'fail'){
                        resolve(result);
                    } else {
                        reject();
                    }
                }catch(e){
                    //TODO handle the exception
                    reject();
                }
            }
        })
    }

  

 

4.使用

IncomeRequest.exportBeforeSettleList({
                        ...this.currentSearchForm
                    }).then(res => {
                        Tools.blobToText(res).then((result)=>{
                            this.showDefaultToast({
                                showClose: true,
                                message: result['resultDesc'],
                                type: 'error',
                                duration: 0
                            });
                        }).catch(()=>{
                            this.showDefaultToast('數據導出成功');
                            Tools.createDownload(res, '文件.xlsx');
                        });
                    });

  

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