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同步调用的资料请关注脚本之家其它相关文章!
相关文章
JavaScript中的常见问题解决方法(乱码,IE缓存,代理)
这篇文章主要是对JavaScript中的常见问题解决方法(乱码,IE缓存,代理)进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所 帮助2013-11-11js编码之encodeURIComponent使用介绍(asp,php)
因此对于JS脚本又重新研究了一下。在对新的URL编码的时候发现,网页编码的格式对于JS的影响很大,在这里书写一点2012-03-03微信小程序Error:Fail to open IDE问题的解决方法
今天学习小程序时无法通过HBuilderX运行微信小程序,查了相关资料后解决了,下面这篇文章主要给大家介绍了关于微信小程序Error:Fail to open IDE问题的解决方法,需要的朋友可以参考下2023-04-04
最新评论