vue实现流下载
流下载的实现方法
在Vue中实现流下载通常涉及从服务器获取二进制数据流,并将其转换为可下载的文件。以下是几种常见的方法:
使用axios实现流下载
axios({
method: 'get',
url: '/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', 'filename.ext')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
使用fetch API实现流下载
fetch('/api/download')
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'filename.ext'
a.click()
window.URL.revokeObjectURL(url)
})
处理大文件下载
对于大文件下载,可以显示下载进度:
axios({
method: 'get',
url: '/api/large-file',
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="filename.ext"
注意事项
确保在下载完成后释放创建的URL对象,避免内存泄漏。对于大文件下载,考虑使用分块下载或断点续传技术。
文件类型处理
根据不同的文件类型,可以设置不同的Blob类型:
new Blob([response.data], { type: 'application/pdf' }) // PDF文件
new Blob([response.data], { type: 'image/png' }) // PNG图片
错误处理
添加错误处理逻辑,捕获可能的网络错误或服务器错误:
axios({...}).catch(error => {
console.error('下载失败:', error)
})






