blob轉換成string格式同步調(diào)用問題解決分析
更新時間:2023年05月23日 09:11:12 作者:甜點cc
這篇文章主要為大家介紹了blob轉換成string格式同步調(diào)用問題解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
問題背景
通過接口下載文件的時候,后端設置的responseHeader
content-disposition: attachment;filename=文件名.xlsx content-type: application/vnd.ms-excel;charset=utf-8
前端接口請求的時候,設置responseType: 'blob',后端接口直接返回的是文件流。
然后當下載文件異常的情況下,接口直接返回的“文件下載出錯”的文字,這個時候業(yè)務組件內(nèi)拿到的返回信息已經(jīng)被轉化成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
}
}定義工具函數(shù)
因為把blob轉成string需要用 FileReader去讀取,FileReader 是異步的,所以這里需要用Promise返回,方便業(yè)務組件同步調(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è)務組件調(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轉string同步調(diào)用問題解決分析的詳細內(nèi)容,更多關于blob轉string同步調(diào)用的資料請關注腳本之家其它相關文章!

