第一种就是get请求啦,点击按钮的时候执行window.location.href或者window.open就可以自动让浏览器去下载对应地址的文件,具体代码如下:
methods: {
// 导出文件
exportFile() {
const downloadURL = '下载接口
const params = '?请求参数'
const requestUrl = downloadURL + params
window.location.href = requestUrl
//或者
window.open(requestUrl)
}
}
如果后端接口使用的是post请求,后端需要先设置:
Content-Type:application/octet-stream
Content-disposition: attachment; filename= 报表.xlsx
前端需要创建一个a标签,通过a标签的href跳转来实现文件下载。
methods: {
// 导出文件
exportFile() {
const downloadURL = '下载接口
const params = {
key:value
}
axios.post(downloadURL,params,{responseType: 'blob'})
.then((res) => {
if(res){
this.openLink(res)
}
})
},
//创建一个看不见的a标签,并点击它
openLink(data) {
const url = window.URL.createObjectURL(new window.Blob([data]));
const link = window.document.createElement('a');
link.style.display = 'none'
link.href = url
link.setAttribute('download', '报表.xlsx')
window.document.body.appendChild(link);
link.click()
}
}