vue实现文件下载demo
Vue 实现文件下载的几种方法
通过 <a> 标签下载
在 Vue 模板中使用 <a> 标签的 download 属性实现文件下载。适用于已知文件 URL 且无需鉴权的场景。
<template>
<a :href="fileUrl" download="filename.pdf">点击下载文件</a>
</template>
<script>
export default {
data() {
return {
fileUrl: 'https://example.com/files/sample.pdf'
}
}
}
</script>
使用 Blob 对象和 URL.createObjectURL
适用于需要从后端获取二进制流或需要处理动态生成文件的场景。
methods: {
downloadFile() {
axios.get('/api/download', { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'file.pdf')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
})
}
}
处理大文件下载(带进度条)
结合 axios 的 onDownloadProgress 实现下载进度显示。
methods: {
downloadWithProgress() {
axios({
url: '/api/large-file',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
console.log(`下载进度: ${percent}%`)
}
}).then(response => {
// 处理文件下载逻辑
})
}
}
后端返回文件流时的处理
当后端返回文件流时,需要正确设置响应头和处理响应数据。
axios.get('/api/export-excel', {
responseType: 'arraybuffer'
}).then(res => {
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'report.xlsx'
a.click()
})
处理需要鉴权的文件下载
对于需要携带 token 的下载请求,需要在请求头中添加认证信息。
axios.get('/api/protected-file', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
responseType: 'blob'
}).then(res => {
// 处理下载逻辑
})
注意事项
- 跨域问题需要后端配合设置 CORS 响应头
- 大文件下载建议分块处理或使用断点续传
- 移动端可能需要特殊处理某些浏览器的兼容性问题
- 下载完成后及时释放创建的 Object URL 避免内存泄漏







