亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

blob轉(zhuǎn)換成string格式同步調(diào)用問題解決分析

 更新時間:2023年05月23日 09:11:12   作者:甜點cc  
這篇文章主要為大家介紹了blob轉(zhuǎn)換成string格式同步調(diào)用問題解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

問題背景

通過接口下載文件的時候,后端設(shè)置的responseHeader

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

前端接口請求的時候,設(shè)置responseType: 'blob',后端接口直接返回的是文件流。

然后當(dāng)下載文件異常的情況下,接口直接返回的“文件下載出錯”的文字,這個時候業(yè)務(wù)組件內(nèi)拿到的返回信息已經(jīng)被轉(zhuǎn)化成blob格式了,所有需要把blob轉(zhuǎn)成 string,用來提示用戶下載異常。

代碼展示

請求響應(yīng)攔截處理

獲取文件流、文件名、文件后綴信息

// 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
  }
}

定義工具函數(shù)

因為把blob轉(zhuǎn)成string需要用 FileReader去讀取,FileReader 是異步的,所以這里需要用Promise返回,方便業(yè)務(wù)組件同步調(diào)用

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('')
    }
  })
}

業(yè)務(wù)組件調(diào)用

// 省略部分代碼
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轉(zhuǎn)string同步調(diào)用問題解決分析的詳細(xì)內(nèi)容,更多關(guān)于blob轉(zhuǎn)string同步調(diào)用的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論