vue下载实现
Vue 下载功能的实现方法
前端实现文件下载
在Vue项目中,前端可以通过以下方式实现文件下载功能:
// 使用Blob对象和URL.createObjectURL
downloadFile(content, fileName) {
const blob = new Blob([content])
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName
link.click()
URL.revokeObjectURL(link.href)
}
后端API接口配合
后端需要提供文件下载接口,返回文件流或文件URL:
// Express示例
app.get('/download', (req, res) => {
const file = `${__dirname}/file.pdf`
res.download(file)
})
使用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', 'file.pdf')
document.body.appendChild(link)
link.click()
})
处理大文件下载
对于大文件下载,可以显示下载进度:
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 => {
// 处理下载
})
浏览器兼容性处理
需要考虑IE浏览器的兼容性:
if (window.navigator.msSaveOrOpenBlob) {
// IE专用方法
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
// 标准方法
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName
link.click()
}
安全注意事项
- 验证文件来源,防止XSS攻击
- 对下载文件名进行编码处理
- 设置合适的CORS策略
- 实现权限验证机制







