前端blob数据类型导出文件(保姆级)

前端通过返回的blob数据类型导出文件(带异常解决)

web端项目开发,后台管理或集成系统居多,多半是数据展示和数据统计为中心的,这种项目就离不开文件的上传和下载,之前我发布了了上传的文章,这次我们来说一下下载,下载其实不难,通常后端返回一个路径,直接就下载了,今天我们说一下另外一种方式通过blob数据类型导出,话不多说直接上代码:
1,第一步封装接口的时候,传responseType字段说明返回的数据类型

//这里是封装接口的时候
exportMonitorData(params){
    
    
      return httpRequest({
    
    
          url: url.exportMonitorData,
          method: 'post',
          responseType: 'blob',//首先我们封装接口的时候要定义好返回的数据类型,传给后端
          data:params,
      })
  },

2,是准备好将blob数据类型转化为文件并下载的方法,作为公共方法调用,因为项目很多地方都会用到

//这个方法封装到你的utils文件里,作为公共方法调用,这是直接导出文件的方法
export function exportData(res, name) {
    
    
  const content = res
  const blob = new Blob([content], {
    
    type: 'application/ms-excel'})
  const fileName = name
  if ('download' in document.createElement('a')) {
    
     // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else {
    
    
    navigator.msSaveBlob(blob, fileName)
  }
}

3,这一步最为关键,主要是异常情况的处理,会有点特殊。

decisionHttp.exportElectricity(params).then(res => {
    
    
    if(res.type === 'application/json'){
    
    //接口返回的数据类型如果是json,说明是报错信息
      let reader = new FileReader();
      reader.readAsText(res, 'utf-8');//这时候你的msg字段是blob类型的,不能直接用,所以数据类型要先转回来
      reader.onload = ()=>{
    
    //这里是处理异步,其他方式用不了,这里很关键
        let {
    
    msg} = JSON.parse(reader.result);//转回来是json类型,再转一次
        this.$message.error(msg); //弹出错误提示
      }
    }else{
    
    
      exportData(res, "用电分析列表.xls");//这里是上面封装的方法,传入res和文件的名字 两个参数就好了
    }
  });

猜你喜欢

转载自blog.csdn.net/m0_52313178/article/details/126474472