vue实现文件下载
Vue 实现文件下载的方法
在 Vue 项目中实现文件下载功能,可以通过以下几种方式实现:
使用 <a> 标签下载
通过动态创建 <a> 标签并设置 download 属性实现文件下载:
<template>
<button @click="downloadFile">下载文件</button>
</template>
<script>
export default {
methods: {
downloadFile() {
const link = document.createElement('a');
link.href = '文件URL或Blob对象';
link.download = '文件名.扩展名';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
</script>
使用 Blob 对象和 URL.createObjectURL
适用于从后端 API 获取文件流或生成动态文件内容:
downloadFile() {
axios.get('API地址', { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.download = '文件名.扩展名';
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(link);
});
}
使用 FileSaver.js 库
安装 FileSaver 库可以简化下载流程:
npm install file-saver
使用示例:
import { saveAs } from 'file-saver';
downloadFile() {
axios.get('API地址', { responseType: 'blob' })
.then(response => {
saveAs(new Blob([response.data]), '文件名.扩展名');
});
}
处理大文件下载
对于大文件下载,可以显示下载进度:

downloadLargeFile() {
axios.get('API地址', {
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(`下载进度: ${percentCompleted}%`);
}
}).then(response => {
// 处理下载完成逻辑
});
}
注意事项
- 确保后端正确设置响应头
Content-Disposition和Content-Type - 跨域请求需要后端配置 CORS 头
- 对于敏感文件,建议通过授权验证后再允许下载
- 大文件下载考虑分片或断点续传方案






