axios 处理二进制流转成图片_解决axios接收二进制流文件乱码问题

1. 须将axios 配置中的responseType设置为arraybuffer,这样就不会让表格出现乱码现象;

2. 如果要动态设置文件名则需要让后台将名字设置到响应头中,否则将是一个乱码的文件名;

3. 然后通过 标签的特性来自动点击下载文件;

4. 如果要兼容IE则需要利用navigator.msSaveOrOpenBlob方法;

5. 兼容Firefox 须将 标签添加到body中,最后再移除 标签

例子:

// axios config

config = {

responseType: 'arraybuffer'

}

// 返回数据处理

getUserInfoExport(data).then(({data,headers}) => {

let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // 将服务端返回的文件流(二进制)excel文件转化为blob

let fileName = headers.filename

if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE

window.navigator.msSaveOrOpenBlob(blob, fileName)

} else {

let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)

let downFile = document.createElement('a')

downFile.style.display = 'none'

downFile.href = objectUrl

downFile.download = fileName // 下载后文件名

document.body.appendChild(downFile)

downFile.click()

document.body.removeChild(downFile) // 下载完成移除元素

// window.location.href = objectUrl

window.URL.revokeObjectURL(objectUrl) // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。

}

})


版权声明:本文为weixin_31968639原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。