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');
                        });
                    });

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM