当前位置:首页 > VUE

vue实现get下载

2026-01-16 02:21:32VUE

Vue 实现 GET 下载

使用 window.open 直接触发下载
适用于简单的 GET 请求下载,无需处理复杂逻辑。直接将文件 URL 通过 window.open 打开,浏览器会自动处理下载。

downloadFile() {
  const fileUrl = 'https://example.com/file.pdf';
  window.open(fileUrl, '_blank');
}

通过 axios 发送 GET 请求并处理二进制流
适用于需要添加请求头或处理后端返回的二进制流数据。

vue实现get下载

import axios from 'axios';

downloadFile() {
  axios({
    url: 'https://example.com/file.pdf',
    method: 'GET',
    responseType: 'blob', // 关键:指定响应类型为二进制流
    headers: {
      Authorization: 'Bearer your_token' // 可选:添加认证头
    }
  }).then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'filename.pdf'); // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url); // 释放内存
  });
}

处理动态文件名
若需从响应头中获取文件名(如后端通过 Content-Disposition 返回文件名):

vue实现get下载

const fileName = response.headers['content-disposition']
  ? response.headers['content-disposition'].split('filename=')[1]
  : 'default.pdf';
link.setAttribute('download', fileName);

注意事项

  • 跨域问题:确保后端配置了 CORS 允许前端域名访问。
  • 大文件下载:建议分片下载或使用后端提供的断点续传接口。
  • 错误处理:添加 catch 块处理网络或权限错误。

完整封装示例

async downloadFile(url, fileName = '') {
  try {
    const response = await axios({
      url,
      method: 'GET',
      responseType: 'blob'
    });
    const actualFileName = fileName || 
      response.headers['content-disposition']?.split('filename=')[1] || 
      'download';
    const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = actualFileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.error('Download failed:', error);
  }
}

标签: vueget
分享给朋友:

相关文章

vue实现视频开场

vue实现视频开场

使用 Vue 实现视频开场动画 在 Vue 中实现视频开场动画可以通过结合 HTML5 的 <video> 标签和 Vue 的过渡效果或生命周期钩子来完成。以下是具体实现方法: 安装依…

vue实现条件判断

vue实现条件判断

Vue 条件判断实现方法 Vue 提供了多种方式实现条件判断,可以根据不同场景选择合适的方式。 v-if / v-else-if / v-else 这是 Vue 中最常用的条件渲染指令,根据表达式…

vue怎么实现选中删除

vue怎么实现选中删除

实现选中删除功能的方法 在Vue中实现选中删除功能通常涉及以下几个关键步骤: 数据绑定与选中状态管理 使用v-model或v-for指令绑定列表数据,结合复选框或单选按钮实现选中状态管理。例如…

vue实现表格多行修改

vue实现表格多行修改

实现多行编辑表格 在Vue中实现表格的多行编辑功能,可以通过以下方法完成。这里以Element UI的表格组件为例,但思路适用于其他UI库或原生实现。 数据准备 定义表格数据和编辑状态管理变量:…

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组件…