vue下载方法实现
下载文件的基本实现
在Vue中实现文件下载功能可以通过前端直接触发下载或通过后端API返回文件流。以下是两种常见方法的实现:
前端直接下载(适用于公开URL文件)
// 方法1:使用<a>标签
const downloadFile = (url, fileName) => {
const link = document.createElement('a')
link.href = url
link.download = fileName || 'download'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
后端API下载(需要处理文件流)

// 方法2:使用axios接收blob数据
import axios from 'axios'
const downloadFromApi = async (apiUrl, fileName) => {
const response = await axios({
url: apiUrl,
method: 'GET',
responseType: 'blob'
})
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.download = fileName || 'file'
document.body.appendChild(link)
link.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(link)
}
封装为Vue组件/指令
可以封装成可复用的组件或指令:
作为方法挂载到Vue原型

// main.js
Vue.prototype.$download = {
file(url, name) {
const link = document.createElement('a')
link.href = url
link.download = name || url.split('/').pop()
link.click()
},
async api(endpoint, name) {
const res = await axios.get(endpoint, { responseType: 'blob' })
const blobUrl = URL.createObjectURL(res.data)
this.file(blobUrl, name)
setTimeout(() => URL.revokeObjectURL(blobUrl), 100)
}
}
使用示例
// 在组件中使用
this.$download.file('/path/to/file.pdf')
this.$download.api('/api/download', 'report.pdf')
处理大文件下载
对于大文件下载需要添加进度提示:
const downloadLargeFile = (url, fileName, onProgress) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onprogress = (event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100)
onProgress && onProgress(percent)
}
}
xhr.onload = () => {
if (xhr.status === 200) {
const blobUrl = URL.createObjectURL(xhr.response)
const link = document.createElement('a')
link.href = blobUrl
link.download = fileName
link.click()
resolve()
} else {
reject(new Error('Download failed'))
}
}
xhr.send()
})
}
注意事项
- 跨域问题:确保下载URL与当前站点同源或配置了CORS
- 文件名处理:后端应在响应头包含
Content-Disposition: attachment; filename="xxx.ext" - 移动端兼容性:部分移动浏览器可能限制程序化下载
- 权限问题:某些浏览器可能阻止非用户触发的下载
以上方法覆盖了Vue项目中最常见的文件下载场景,可根据实际需求选择合适方案。






