vue实现文件下载a
Vue 实现文件下载的方法
使用 <a> 标签下载
通过动态创建 <a> 标签实现文件下载。适用于已知文件 URL 的情况:
downloadFile(url, fileName) {
const link = document.createElement('a')
link.href = url
link.download = fileName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
使用 Blob 对象下载
当需要下载后端返回的二进制流数据时,可以通过 Blob 对象处理:
downloadBlob(data, fileName, fileType) {
const blob = new Blob([data], { type: fileType })
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = fileName
link.click()
window.URL.revokeObjectURL(url)
}
结合 Axios 下载
处理需要认证的文件下载请求:
axios({
url: '/api/download',
method: 'GET',
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'filename.ext')
document.body.appendChild(link)
link.click()
})
处理大文件下载
对于大文件下载,可以显示进度条:
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 => {
// 处理下载完成逻辑
})
注意事项
- 确保服务器正确设置 Content-Disposition 响应头
- 跨域请求需要服务器配置 CORS 头
- 移动端可能需要特殊处理某些浏览器的兼容性问题
- 文件类型应正确指定 MIME 类型
以上方法可根据具体需求选择使用,通常组合使用 Blob 和 Axios 能覆盖大多数文件下载场景。







