vue调用下载文件接口
时间: 2023-10-14 14:28:17 浏览: 124
可以通过以下步骤实现在 Vue 中调用下载文件接口:
1. 定义一个下载文件的方法:
```javascript
downloadFile() {
// 发送下载请求
axios({
url: '/api/download', // 接口地址
method: 'get',
responseType: 'blob' // 表明返回服务器返回的数据类型
}).then(response => {
const blob = new Blob([response.data])
const fileName = 'file.xlsx' // 文件名,从接口返回值获取
const linkNode = document.createElement('a')
linkNode.download = fileName // a 标签的 download 属性指定下载文件的文件名
linkNode.style.display = 'none'
linkNode.href = URL.createObjectURL(blob)
document.body.appendChild(linkNode)
linkNode.click()
document.body.removeChild(linkNode) // 下载完成移除元素
})
}
```
2. 在 Vue 组件中调用该方法:
```html
<template>
<button @click="downloadFile">下载文件</button>
</template>
<script>
import axios from 'axios'
export default {
methods: {
downloadFile() {
// 上面定义的下载文件方法
// ...
}
}
}
</script>
```
注意:这里使用了 axios 发送请求,需要安装 axios 并引入。
阅读全文
相关推荐


















