1.当a标签herf属性的路径为同源路径时,则可以模拟点击事件实现文件下载,不为同源路径则在浏览器窗口跳转到新的页面(同源表示 域名,端口,协议相同)
function download(){
const a = document.createElement("a")
a.href = getServerUrl() + path
a.download = "true"
document.body.append(a)
a.click()
document.body.removeChild(a)
}
2.当下载的路径不为同源路径时,可以先将文件数据请求到, 以文件流方式数据保存,通过URL.createObjectURL(blob)作为a标签的路径 传入然后模拟下载
function getData(){
axios.post('/server/getData/url').then(res=>{
downloadByBlob(res.data,'text/csv')
})
}
// type类型参考这里 https://www.iana.org/assignments/media-types/media-types.xhtml
function downloadByBlob(data,type){
const a = document.createElement("a")
const blob = new Blob([data],{type:type})
a.href = URL.createObjectURL(blob)
// 获取文件名称 参考//https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a#download
//a.download = "filename"
document.body.append(a)
a.click()
document.body.removeChild(a)
}