vue如何实现文件下载
Vue 实现文件下载的方法
使用 <a> 标签下载
通过动态创建 <a> 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 对象的情况。
<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 对象下载
适用于从 API 获取二进制数据(如后端返回的文件流)的场景。
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 = '自定义文件名.pdf';
link.click();
window.URL.revokeObjectURL(url);
});
使用 FileSaver.js 库
通过第三方库简化下载流程,支持更复杂的文件类型处理。

安装依赖:
npm install file-saver
使用示例:

import { saveAs } from 'file-saver';
// 保存文本
saveAs(new Blob(['文件内容'], { type: 'text/plain' }), 'example.txt');
// 保存图片
fetch('image.png').then(res => res.blob()).then(blob => {
saveAs(blob, 'image.png');
});
处理后端返回的文件流
当后端返回文件流时,需正确设置响应类型和头部信息。
axios({
method: 'get',
url: '下载接口',
responseType: 'blob'
}).then(res => {
const blob = new Blob([res.data]);
const fileName = res.headers['content-disposition']
? res.headers['content-disposition'].split('filename=')[1]
: 'default_name';
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = decodeURIComponent(fileName);
link.click();
});
大文件分块下载
对于大文件下载,可采用分块处理方式优化体验。
async function downloadLargeFile(url, fileName) {
const response = await fetch(url);
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
const chunks = [];
while(true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
receivedLength += value.length;
console.log(`下载进度: ${(receivedLength / contentLength * 100).toFixed(2)}%`);
}
const blob = new Blob(chunks);
saveAs(blob, fileName);
}
注意事项
- 跨域问题需确保服务器配置正确的 CORS 头
- 移动端部分浏览器可能限制自动下载行为
- 文件名中文乱码问题建议使用
decodeURIComponent处理 - 大文件下载建议显示进度条提升用户体验






