vue实现get下载
Vue 实现 GET 下载
方法一:使用 window.open 或 a 标签
直接通过浏览器原生方式触发下载,适用于简单的 GET 请求下载场景。
// 方式1:直接通过 window.open 触发
window.open('/api/download?fileId=123', '_blank');
// 方式2:动态创建 a 标签并触发点击
const link = document.createElement('a');
link.href = '/api/download?fileId=123';
link.download = 'filename.ext'; // 可选,设置下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
方法二:使用 axios 处理二进制流
适用于需要添加请求头或处理权限验证等复杂场景,后端需返回二进制流。
axios({
method: 'get',
url: '/api/download',
responseType: 'blob', // 关键:指定响应类型为二进制流
params: { fileId: 123 }
}).then(response => {
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'filename.ext'; // 从响应头或自定义文件名
link.click();
window.URL.revokeObjectURL(url); // 释放内存
});
方法三:从响应头获取文件名
如果后端通过 Content-Disposition 返回文件名,可通过以下方式解析:

const contentDisposition = response.headers['content-disposition'];
const fileName = contentDisposition.split('filename=')[1].replace(/"/g, '');
注意事项
- 跨域问题:确保后端配置了
Access-Control-Expose-Headers暴露Content-Disposition等自定义头 - 错误处理:添加
catch处理网络或服务端错误 - 大文件下载:建议使用分块下载或进度提示
- 权限控制:可在请求头中添加
Authorization等验证信息
完整示例(结合方法二和三)
axios.get('/api/download', {
params: { fileId: 123 },
responseType: 'blob'
}).then(response => {
let fileName = 'default.ext';
const disposition = response.headers['content-disposition'];
if (disposition && disposition.indexOf('filename=') !== -1) {
fileName = decodeURIComponent(
disposition.split('filename=')[1].split(';')[0].replace(/"/g, '')
);
}
const blob = new Blob([response.data]);
const downloadUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(downloadUrl);
}, 100);
}).catch(error => {
console.error('下载失败:', error);
});






