<script setup></script>
<template>
<div>
<button><a :href="fileUrl" download>点击下载文件1 - a标签</a></button>
</div>
<hr />
<div>
<button @click="downloadFile">点击下载文件2 - blob</button>
</div>
<hr />
<div>
<button @click="downloadFile2">点击下载文件3 - window.location.href</button>
</div>
</template>
<script>
export default {
data() {
return {
fileUrl: 'http://localhost:9090/cardpro/card/system/login/export/api' // 替换为你要下载的文件的实际路径
}
},
methods: {
async downloadFile() {
const url = 'http://localhost:9090/cardpro/card/system/login/export/api'
const response = await fetch(url) //发送GET请求
if (response.ok) {
const blob = await response.blob() //获取Blob对象
const url = window.URL.createObjectURL(blob) //创建Blob对象的URL
const link = document.createElement('a') //创建一个新的<a>元素
link.href = url //设置<a>元素的href属性为Blob对象的URL
link.download = 'filename.xlsx' //设置下载文件的文件名
document.body.appendChild(link) //将<a>元素添加到文档中
link.click() //模拟点击<a>元素以触发文件下载
} else {
//处理API响应失败的情况,例如显示错误消息
}
},
async downloadFile2() {
window.location.href =
'http://localhost:9090/cardpro/card/system/login/export/api'
}
}
}
</script>
<style scoped></style>
vue中三种下载文件方式(太烂了)
于 2023-12-05 15:32:44 首次发布