项目需求导出execl文件,以前的做法是创建文件提供url地址下载,这次接口是没有返回信息的,返回的数据在response中并且是二进制流,在网上查看了相关资料解决了该问题。
首先在前端请求中 加入红色部分
//导出
export function exportList(data) {
return request({
url: '/user/gift/getListToExcel',
method: 'post',
responseType: 'blob',
data:data
})
}
由于使用了若依框架 所以在拦截器处做了一些修改
// 响应拦截器
service.interceptors.response.use(res => {
if(res.data.hasOwnProperty('code')){
//处理导出接口没有返回 result 只返回了二进制流的情况
// todo 正常的拦截逻辑
}else {
// 直接返回,用于下一步获取res
return res.data
}
}
然后处理返回的数据
exportList(params).then(res => {
let blob = new Blob([res], {
type: 'application/vnd.ms-excel'
})
let objectUrl = URL.createObjectURL(blob)
let a = document.createElement('a')
a.href = objectUrl
a.download = formatDate(new Date()) // 文件名 ,
// a.click();
// 下面这个写法兼容火狐
a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}))
window.URL.revokeObjectURL(blob)
})
具体的一些细节可能还需要根据自身项目进行修改。参考文档https://www.freesion.com/article/4685133862/