vue下载功能实现
实现 Vue 文件下载功能
前端实现方案(基于 axios)
// 在 Vue 组件中
methods: {
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)
})
}
}
后端实现方案(Node.js Express 示例)
app.get('/api/download', (req, res) => {
const filePath = path.join(__dirname, 'files', 'sample.pdf')
res.download(filePath, 'custom-filename.pdf', (err) => {
if (err) {
res.status(500).send('Download failed')
}
})
})
前端直接下载方案(无需后端)
downloadTextFile() {
const content = 'Hello, this is a text file!'
const blob = new Blob([content], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'example.txt'
a.click()
URL.revokeObjectURL(url)
}
处理大文件下载
对于大文件下载,可以添加进度提示:
axios({
url: '/api/large-file',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
console.log(percentCompleted + '% downloaded')
}
})
安全注意事项
确保后端实现适当的权限检查,防止未授权访问。可以在下载前验证用户权限:

// Express 中间件示例
function checkDownloadPermission(req, res, next) {
if (req.user.hasDownloadPermission) {
next()
} else {
res.status(403).send('Forbidden')
}
}
app.get('/api/download', checkDownloadPermission, (req, res) => {
// 处理下载逻辑
})






