vue如何实现下载文件的功能
时间: 2024-05-06 15:21:07 浏览: 7
Vue 可以通过创建一个链接或者 XMLHttpRequest 请求来实现文件下载。其中,创建链接方法如下:
```javascript
axios({
url: 'your/file/url',
method: 'GET',
responseType: 'blob',
}).then(res => {
const link = document.createElement('a')
const blob = new Blob([res.data])
const objectUrl = URL.createObjectURL(blob)
link.href = objectUrl
link.download = 'your-file-name'
link.click()
})
```
而使用 XMLHttpRequest 方法如下:
```javascript
axios({
url: 'your/file/url',
method: 'GET',
responseType: 'blob',
}).then(res => {
if (window.navigator.msSaveOrOpenBlob) {
// 兼容 IE
navigator.msSaveBlob(res.data, 'your-file-name')
} else {
const link = document.createElement('a')
const blob = new Blob([res.data])
const objectUrl = URL.createObjectURL(blob)
link.href = objectUrl
link.setAttribute('download', 'your-file-name')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
})
```
希望以上方法可以帮助你实现下载文件的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)