vue实现异步下载
异步下载的实现方法
在Vue中实现异步下载通常涉及前端发起请求并处理文件流。以下是几种常见方法:
使用axios下载文件
通过axios发起GET请求获取文件流,利用Blob对象和URL.createObjectURL生成下载链接:
downloadFile() {
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()
document.body.removeChild(link)
})
}
使用fetch API实现
fetch API同样可以处理文件下载,代码更简洁:
async downloadWithFetch() {
const response = await fetch('/api/download')
const blob = await response.blob()
const downloadUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = downloadUrl
a.download = 'file.ext'
a.click()
URL.revokeObjectURL(downloadUrl)
}
处理大文件下载
对于大文件下载,可以显示下载进度:
downloadLargeFile() {
axios({
url: '/api/large-file',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
console.log(percentCompleted + '%')
}
}).then(response => {
// 处理下载完成逻辑
})
}
服务器端要求
后端接口需要正确设置响应头:
Content-Type: application/octet-streamContent-Disposition: attachment; filename="file.ext"
错误处理
添加错误处理增强用户体验:
downloadFile().catch(error => {
console.error('下载失败:', error)
// 显示错误提示
})
这些方法可以根据具体需求选择或组合使用,适用于大多数文件下载场景。







