前端post请求下载excel文件,无法打开
problem
前端post请求后,拿到数据下载excel文件,但是报错:文件无法打开
大致过程:
前端:调用后端 post ajax 请求后端:返回的文件流 content-disposition: attachment前端:拿到二进制文件流 blob 转成 url,然后用 js 模拟 a标签,然后触发download
reason
如果发现导出的文件格式错误,打不开,多半是responseType的错误 后端返回二进制数据,需要前端正确处理 才能使用
solution
解决办法:
axios responseType设置为 blob/arrayBuffer 都可以实际 axios.responseType 对应的是 XMLHttpRequest.responseType
export function exportData(data) {
return request({
url: '/task/export',
method: 'post',
// 添加配置:blob arraybuffer 都可以
responseType: 'blob',
data
})
}
精彩链接
发表评论