vue实现get下载
使用 Vue 实现 GET 下载
方法一:通过 window.open 直接下载
直接通过 window.open 打开下载链接,适用于简单的文件下载场景。
downloadFile() {
const url = 'https://example.com/file.pdf';
window.open(url, '_blank');
}
方法二:使用 axios 发送 GET 请求
通过 axios 发送 GET 请求获取文件流,并使用 Blob 对象创建下载链接。
import axios from 'axios';
downloadFile() {
axios({
url: 'https://example.com/file.pdf',
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', 'file.pdf');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
方法三:处理带认证的下载
如果下载接口需要认证(如 Token),可以在请求头中添加认证信息。
downloadFileWithAuth() {
const token = localStorage.getItem('token');
axios({
url: 'https://example.com/protected-file.pdf',
method: 'GET',
responseType: 'blob',
headers: {
'Authorization': `Bearer ${token}`
}
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'protected-file.pdf');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
方法四:处理后端返回的文件名
如果后端在响应头中返回文件名,可以通过解析 content-disposition 获取。
downloadFileWithDynamicName() {
axios({
url: 'https://example.com/dynamic-file',
method: 'GET',
responseType: 'blob',
}).then(response => {
const contentDisposition = response.headers['content-disposition'];
const fileName = contentDisposition.split('filename=')[1];
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
方法五:通过 fetch 实现下载
如果不使用 axios,可以通过原生 fetch 实现下载。

downloadWithFetch() {
fetch('https://example.com/file.pdf')
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
注意事项
- 确保后端接口支持跨域请求(CORS),否则下载可能失败。
- 如果文件较大,可以添加加载提示以改善用户体验。
- 下载完成后,记得释放 Blob URL 以避免内存泄漏。
// 释放 Blob URL
window.URL.revokeObjectURL(url);
以上方法涵盖了 Vue 中实现 GET 下载的常见场景,可以根据实际需求选择合适的方式。






