文件下载返回乱码处理 vue+axios
后端返回数据流是乱码,可以使用new Blob()
这个方法处理,可以解决乱码问题。
1、乱码返回结果如下:
2、解决方法:
async postClick() {
const res = await axios({
url: '后端接口',
method: 'post',
data: { id: '文件id' }
responseType: 'blob'
})
const content = res.data
const fileName = 'a.png' // 文件名称
// 如果不确定文件类型,type可以写空字符串
const bolb = new Blob([content], { type: '' })
if ('download' in document.createElement('a')) {
const link = document.createElement('a')
link.download = fileName
link.style.display = 'none'
// URL.createObjectURL(bolb) = blob:http://localhost:8080/a34a8a20-acf2-3f21-bc22-45994d9f0290
link.href = URL.createObjectURL(bolb)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
}
}