前端Blob转String同步调用异常处理方案

作者:木棉时间:2026-10-30 19:17:59浏览:149

本文分析前端接口下载文件时,后端返回Blob格式导致异常信息无法直接读取的问题。通过封装FileReader并返回Promise,实现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)
  }
}

以上为Blob转String同步调用问题的详细解决方案,如需了解更多关于Blob转String同步调用的内容,请查阅本站其他相关文章。

作者最新文章