参数必须加responseType: ‘blob’,不然会乱码
axios.get(url, {
params: {
...params
},
responseType: 'blob'
})
.then(res => {
if (!res) return
let url = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
//文件名加上当前时间
let time = moment(new Date().getTime()).format('YYYYMMDDHHmmss')
//如果请求头里返回文件名,则直接使用请求头的文件名;若没,则使用页面中设置的
let finalFileName = res.headers['content-disposition'] ? res.headers['content-disposition'].split('=')[1]: `${fileName}_${time}.${fileTypes}`
link.setAttribute('download', finalFileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(a)
})
.catch(err => {
console.log(err)
})

本文介绍如何使用Axios从服务器正确下载文件,避免文件内容出现乱码。关键在于设置responseType为'blob',并展示了如何通过Blob处理响应数据,生成文件链接,实现自动下载。
1505

被折叠的 条评论
为什么被折叠?



