数据导出成文档,是一个常规功能:
最简单的方式就是,对应的a标签的href属性指向后台导出接口的url,参数紧跟在url的?后面
注意,如果参数中涉及中文,记得encodeURI处理,兼容ie浏览器
这种方法,缺点在于
该接口报错,无法进行相应处理
ie无法识别download属性,无法给文件赋中文名(想要ie中文的下载文档,后台处理后传回)
如果想要自己控制请求的流程,提供一个样例:
axios.get(
url,
{ responseType: 'blob' }
).then((response) => {
if (response) {
let url = (window.URL) ? window.URL.createObjectURL(response.data || response) : window.webkitURL.createObjectURL(response.data || response)
if ('msSaveOrOpenBlob' in navigator) { // IE导出
window.navigator.msSaveOrOpenBlob(response.data, fileName)
} else {
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
link.remove()
}
} else {
console.log('下载请求数据异常---')
}
})