Skip to content

文件下载处理

问题

axios 设置 responseType:Blob,后台返回的数据会被强制转为blob类型,这时后台返回的数据会有两种情况要处理

情况1

数据异常,后台返回 blob 类型异常信息,使用 new FileReader(),将 blob 转为 json,然后进行处理

情况2

数据正常,后台返回 blob 文件流:

解决

javascript
getBusinessDataPdf(params)
  .then((res) => {  
    let reader = new FileReader();  
    reader.readAsText(res)  
       reader.onload = function (result) {  
           try {  
               //1.解析对象成功,说明是json数据 
               let resData = JSON.parse(result.target.result);  
               if (resData.code) {  
                   $message.error(resData.message)    
               }  
           } catch (err) {  
               //2.解析成对象失败,说明是正常的文件流  
               let blob = new Blob([res], { type: "application/pdf" });  
               
           }  
       }  
})
  .catch(() => {  
    $message.error('pdf下载出错,请重试')    
})

文件下载方法

javascript
const downLoadBlobFile = (data: Blob, fileName?: string, type?: string) => { 		//type为Mime类型
  let name = fileName || new Date().toLocaleDateString();
  let typeStr = type ? type : 'application/vnd.ms-excel';

  if (window.navigator.msSaveOrOpenBlob) {  //兼容性处理
    const blob = new Blob([data], { type: typeStr });
    navigator.msSaveBlob(blob, name);
  } else {
    const excelBlob = new Blob([data], { type: typeStr });
    let oa = document.createElement('a');
    oa.href = URL.createObjectURL(excelBlob);
    oa.download = name;
    document.body.appendChild(oa);
    oa.click();
    window.URL.revokeObjectURL(oa.href);
    document.body.removeChild(oa);
  }
};

Released under the MIT License.