vue 实现附件下载
实现附件下载的基本方法
在Vue中实现附件下载通常通过前端生成下载链接或调用后端API完成。以下是几种常见实现方式:
使用<a>标签直接下载
对于静态文件或已知URL的资源,可直接使用HTML的<a>标签:
<template>
<a href="/path/to/file.pdf" download="filename.pdf">下载文件</a>
</template>
download属性指定保存时的默认文件名。
通过Blob对象实现动态下载
当需要从API获取文件数据时,可使用Blob对象:
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()
link.remove()
window.URL.revokeObjectURL(url)
})
处理后端返回的文件流
对于后端返回的文件流,需要正确设置响应类型:
async function downloadFile() {
try {
const res = await axios({
method: 'get',
url: '/api/file',
responseType: 'blob'
})
const blob = new Blob([res.data])
const downloadUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = downloadUrl
a.download = 'document.pdf'
document.body.appendChild(a)
a.click()
URL.revokeObjectURL(downloadUrl)
a.remove()
} catch (error) {
console.error('下载失败:', error)
}
}
处理权限验证
需要验证权限时,可在请求头中添加token:
axios.get('/api/protected-file', {
responseType: 'blob',
headers: {
'Authorization': `Bearer ${store.state.token}`
}
})
显示下载进度
对于大文件下载,可添加进度提示:
axios.get('/api/large-file', {
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
console.log(`下载进度: ${percent}%`)
}
})
处理不同文件类型
根据文件类型设置正确的MIME类型:
const fileType = 'application/pdf'
const blob = new Blob([response.data], { type: fileType })
错误处理
添加适当的错误处理逻辑:
axios.get('/api/download')
.catch(error => {
if (error.response.status === 404) {
alert('文件不存在')
} else {
alert('下载失败')
}
})
封装为可复用组件
可将下载逻辑封装为可复用组件:
<template>
<button @click="downloadFile">下载</button>
</template>
<script>
export default {
methods: {
async downloadFile() {
// 实现下载逻辑
}
}
}
</script>






