使用< a>标签
<a href="../../static/xxx.xlsx" download="xxx.xlsx">下载</a>
直接点击可以下载,需要注意的是download属性,当不加download属性时,如果文件格式为txt、pdf、jpg等浏览器支持直接打开的文件格式,那么不会下载,而是浏览器直接打开;添加download属性之后,就会下载,并且下载文件默认命名为你download属性的值
使用window.open()
window.open("../../static/xxx.xlsx")
window.open("https://cee/edit/xxx.xlsx")
返回值得处理,其实也是< a>标签
首先是请求接口会返回res,需要注意请求一定要加 responseType: "blob"
哦!然后再调用下面封装的方法即可
axios.get({
url: 'xxxxxx',
method: 'get',
data:{},
responseType: 'blob'
}).then(res => {});
ExportCSV(res) {
const blob = new Blob([res.data], {
type: "application/vnd.ms-excel"
})
const filename = decodeURI((res.headers['content-disposition'] && res.headers['content-disposition'].split(';')[1].split('=')[1])) || 'file.xls'
// 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const elink = document.createElement('a')
elink.download = filename
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
}
}