vue前端实现文件下载
使用 window.open 直接下载
通过 window.open 直接打开文件链接触发下载,适用于简单的文件下载场景。
将文件 URL 作为参数传入,浏览器会自动处理下载行为:
window.open('https://example.com/file.pdf', '_blank');
使用 <a> 标签动态触发下载
创建隐藏的 <a> 标签,设置 download 属性后模拟点击,适合需要自定义文件名的情况:
const link = document.createElement('a');
link.href = 'https://example.com/file.pdf';
link.download = 'custom-filename.pdf'; // 指定下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
通过 Blob 对象下载二进制数据
当需要处理后端返回的二进制流(如 Axios 响应)时,可通过 Blob 转换并下载:
axios.get('/api/download', { responseType: 'blob' }).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.download = 'file.zip';
link.click();
window.URL.revokeObjectURL(url); // 释放内存
});
处理大文件分片下载
对于大文件下载,可结合 Content-Range 实现分片下载与合并:
async function downloadLargeFile(url, fileName, chunkSize = 1024 * 1024) {
let startByte = 0;
const chunks = [];
while (true) {
const response = await fetch(url, {
headers: { 'Range': `bytes=${startByte}-${startByte + chunkSize}` }
});
if (!response.ok) break;
chunks.push(await response.blob());
startByte += chunkSize;
}
const blob = new Blob(chunks);
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
添加下载进度提示
通过 Axios 的 onDownloadProgress 实现进度显示:
axios({
url: '/api/download',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
console.log(`下载进度: ${percent}%`);
}
}).then(response => {
// 处理下载完成逻辑
});
注意事项
- 跨域问题需确保服务器配置
Access-Control-Allow-Origin - 部分浏览器可能限制非用户触发的下载行为,建议在按钮点击事件中触发
- 移动端需测试兼容性,部分浏览器对
download属性支持有限







