当前位置:首页 > VUE

vue实现get下载

2026-03-29 02:40:33VUE

Vue 实现 GET 下载

方法一:使用 window.opena 标签

直接通过浏览器原生方式触发下载,适用于简单的 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 返回文件名,可通过以下方式解析:

vue实现get下载

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);
});

标签: vueget
分享给朋友:

相关文章

vue实现压缩上传文件

vue实现压缩上传文件

压缩上传文件的实现方法 在Vue中实现文件压缩和上传功能,可以通过以下步骤完成。该方法结合了前端文件压缩库和HTTP请求,确保文件在上传前被有效压缩。 安装必要的依赖 需要使用compressorj…

vue实现逻辑

vue实现逻辑

Vue 实现逻辑的核心概念 Vue.js 是一个渐进式 JavaScript 框架,其核心逻辑围绕数据驱动和组件化开发。通过响应式系统、虚拟 DOM 和组件生命周期等机制,Vue 实现了高效的前端开发…

vue实现接口

vue实现接口

在 Vue 中实现接口请求 Vue 本身不直接提供 HTTP 请求功能,通常需要借助第三方库如 axios 或 fetch 来实现接口请求。以下是几种常见方法: 使用 axios 发送请求 安装 a…

vue拖动实现

vue拖动实现

实现 Vue 拖动功能的方法 使用 HTML5 拖放 API 在 Vue 中可以利用 HTML5 的原生拖放 API 实现拖动功能。通过 draggable 属性标记可拖动元素,结合 @dragsta…

vue 实现评分

vue 实现评分

Vue 实现评分功能 在 Vue 中实现评分功能可以通过多种方式完成,包括使用第三方组件库或自定义实现。以下是两种常见的方法: 使用第三方组件库(如 Element UI) Element UI 提…

vue实现答题

vue实现答题

Vue 实现答题功能 数据结构设计 使用 Vue 的响应式特性管理题目和答案数据。通常需要以下数据结构: data() { return { questions: [ {…