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

  

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