vue实现文件下载
使用 <a> 标签下载文件
通过动态创建 <a> 标签实现文件下载,适用于已知文件 URL 的情况。
在 Vue 组件中定义方法,动态设置 href 和 download 属性,触发点击事件。
methods: {
downloadFile(url, fileName) {
const link = document.createElement('a');
link.href = url;
link.download = fileName || 'file';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
通过 Blob 对象下载动态内容
当需要下载后端返回的二进制流(如 Axios 响应)时,可将数据转换为 Blob 对象,生成临时 URL。
axios.get('/api/download', { responseType: 'blob' }).then(response => {
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
this.downloadFile(url, 'example.pdf'); // 复用前例方法
window.URL.revokeObjectURL(url); // 释放内存
});
处理后端文件名
若后端通过响应头返回文件名,可从 content-disposition 头中提取:
const contentDisposition = response.headers['content-disposition'];
const fileName = contentDisposition.split('filename=')[1].trim();
大文件分块下载
对于大文件,可采用流式处理避免内存问题,使用 fetch 和 ReadableStream:
async function downloadLargeFile(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
const blob = new Blob(chunks);
const objectUrl = URL.createObjectURL(blob);
this.downloadFile(objectUrl, 'large_file.zip');
}
进度显示实现
通过 Axios 的 onDownloadProgress 事件实现下载进度条:
axios.get('/api/file', {
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
console.log(`下载进度: ${percent}%`);
}
}).then(response => {
// 处理下载完成逻辑
});






