当前位置:首页 > 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 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue实现流程

vue实现流程

Vue 实现流程的基本步骤 安装 Vue.js 可以通过 CDN 引入或使用 npm/yarn 安装。 CDN 方式: <script src="https://cdn.jsdelivr.…

vue底层实现

vue底层实现

Vue.js 的底层实现原理 Vue.js 是一个渐进式 JavaScript 框架,其核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是其关键实现细节: 响应式系统 Vue 2…

vue环境实现

vue环境实现

Vue 环境搭建 安装 Node.js 和 npm Node.js 是运行 Vue 的基础环境,npm 是包管理工具。从 Node.js 官网 下载并安装最新稳定版本。安装完成后,在终端运行以下命令验…

vue实现ide

vue实现ide

Vue 实现 IDE 的基本思路 使用 Vue 构建一个简易的集成开发环境(IDE)需要整合代码编辑器、文件管理、终端模拟等功能。以下是关键实现步骤和推荐工具。 核心功能模块 代码编辑器 使用…

vue 实现跳转

vue 实现跳转

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转通常可以通过以下几种方式实现,具体选择取决于项目需求和技术栈(如是否使用 Vue Router)。 使用 Vue Router 进行编程式导航…