关于前端: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

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

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据