乐趣区

关于前端:blob转string同步调用

问题背景

通过接口下载文件的时候,后端设置的responseHeader

content-disposition: attachment;filename= 文件名.xlsx
content-type: application/vnd.ms-excel;charset=utf-8

前端接口申请的时候,设置responseType: 'blob',后端接口间接返回的是文件流。

而后当下载文件异样的状况下,接口间接返回的“文件下载出错”的文字,这个时候业务组件内拿到的返回信息曾经被转化成 blob 格局了,所有须要把 blob 转成 string,用来提醒用户下载异样。

代码展现

申请响应拦挡解决

获取文件流、文件名、文件后缀信息

// content-disposition: attachment;filename= 文件名.xlsx
const contentDisposition = response.headers['content-disposition']

const _fileName = contentDisposition.split('=')[1]

const fileType = _fileName.substring(_fileName.lastIndexOf('.')); // .xlsx
const fileName = _fileName.substring(0, _fileName.lastIndexOf('.')); // 文件名

if (fileName && fileType) {
  return {
    data: response.data,
    fileName,
    fileType
  }
}

定义工具函数

因为把 blob 转成 string 须要用 FileReader去读取,FileReader 是异步的,所以这里须要用 Promise 返回,不便业务组件同步调用

export const downloadFile = (srcData, fileName='下载', fileType='.xls', target='_self') {var blob = new Blob([srcData])
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    // 兼容 IE/Edge
    window.navigator.msSaveOrOpenBlob(blob, fileName + fileType)
  } else {var url = window.URL.createObjectURL(blob)
    var a = document.createElement('a')
    a.href = url
    a.target = target
    a.style.display = 'none'
    a.setAttribute('download', fileName + fileType)
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url) // 开释资源
  }
}

export const blobToString = (blobData) => {return new Promise((resolve) => {if (blobData instanceof Blob) {const reader = new FileReader();
      reader.readAsText(blobData, 'utf-8')
      reader.onload = function () {resolve(reader.result || '')
      }
    } else {resolve('')
    }
  })
}

业务组件调用

// 省略局部代码
async down() {
  try {const res = await API();

    const {data, fileName, fileType, code} = res || {}
    
    if (code === -1) {const result = await blobToString(data)
      this.$message.error(result)
      return
    }

    downloadFile(data, fileName, fileType)
  } catch (err) {console.log(err)
  }
}

我是 甜点 cc

公众号:【看见另一种可能】

退出移动版