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';
link.download = '文件名.扩展名';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
</script>
使用 axios 下载文件

对于需要认证或处理二进制数据的场景,可以使用 axios:
axios({
url: '文件API地址',
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', '文件名.扩展名');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
处理后端返回的文件流
当后端返回文件流时,可以这样处理:

fetch('API地址')
.then(res => res.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '文件名';
a.click();
window.URL.revokeObjectURL(url);
});
注意事项
- 跨域问题需要后端配置 CORS 头信息
- 大文件下载建议显示进度条
- 移动端可能需要特殊处理
- 确保服务器正确设置了文件 MIME 类型
扩展功能
可以添加下载进度显示:
axios({
url: '文件地址',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(percentCompleted);
}
})
以上方法涵盖了 Vue 项目中实现文件下载的主要场景,开发者可以根据具体需求选择适合的方案。






