当前位置:首页 > VUE

vue实现get下载

2026-02-17 03:37:37VUE

vue实现get下载

使用axios发起GET请求下载文件,结合Blob对象和URL.createObjectURL实现文件下载。

vue实现get下载

<template>
  <button @click="downloadFile">下载文件</button>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    async downloadFile() {
      try {
        const response = await axios.get('https://example.com/file.pdf', {
          responseType: 'blob'
        });

        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);
      } catch (error) {
        console.error('下载失败:', error);
      }
    }
  }
};
</script>

处理后端返回的文件流

当后端返回文件流时,需要正确设置响应类型并处理Blob数据。

vue实现get下载

async downloadStream() {
  const response = await axios.get('/api/download', {
    responseType: 'blob',
    params: {
      fileId: '123'
    }
  });

  const contentDisposition = response.headers['content-disposition'];
  let fileName = 'default.pdf';
  if (contentDisposition) {
    const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/);
    if (fileNameMatch.length > 1) {
      fileName = fileNameMatch[1];
    }
  }

  const blobUrl = URL.createObjectURL(response.data);
  const a = document.createElement('a');
  a.href = blobUrl;
  a.download = fileName;
  a.click();
  URL.revokeObjectURL(blobUrl);
}

添加下载进度显示

通过axios的onDownloadProgress回调显示下载进度。

async downloadWithProgress() {
  const response = await axios.get('/large-file.zip', {
    responseType: 'blob',
    onDownloadProgress: progressEvent => {
      const percentCompleted = Math.round(
        (progressEvent.loaded * 100) / progressEvent.total
      );
      console.log(`下载进度: ${percentCompleted}%`);
      // 可以更新UI显示进度
    }
  });

  // 处理下载完成后的逻辑
}

处理大文件分片下载

对于大文件,可以考虑实现分片下载以提高可靠性。

async downloadLargeFile() {
  const CHUNK_SIZE = 1024 * 1024; // 1MB
  let receivedBytes = 0;
  let chunks = [];

  while(true) {
    const response = await axios.get('/large-file', {
      responseType: 'blob',
      headers: {
        'Range': `bytes=${receivedBytes}-${receivedBytes + CHUNK_SIZE - 1}`
      }
    });

    if (response.status === 206) {
      chunks.push(response.data);
      receivedBytes += response.data.size;
    } else if (response.status === 200) {
      chunks.push(response.data);
      break;
    }

    if (response.data.size < CHUNK_SIZE) {
      break;
    }
  }

  const completeBlob = new Blob(chunks);
  const url = URL.createObjectURL(completeBlob);
  // 创建下载链接...
}

注意事项

  • 确保服务器支持CORS,否则跨域请求会被浏览器拦截
  • 下载完成后及时调用URL.revokeObjectURL释放内存
  • 对于敏感文件,考虑添加权限验证
  • 处理可能的网络错误和超时情况
  • 移动端可能需要特殊处理某些浏览器的下载行为

标签: vueget
分享给朋友:

相关文章

vue实现双折线图

vue实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 ECh…

vue实现功能

vue实现功能

Vue 功能实现方法 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是实现常见功能的几种方法: 数据绑定与响应式更新 在 Vue 中,数据绑定通过 v-mode…

vue实现switch

vue实现switch

Vue 实现 Switch 开关组件 在 Vue 中实现 Switch 开关组件可以通过自定义组件或使用现有 UI 库完成。以下是几种常见实现方式: 自定义 Switch 组件 创建一个基础…

vue实现返回

vue实现返回

返回按钮功能实现 在Vue中实现返回功能通常有两种方式:使用浏览器历史记录的history.back()或结合Vue Router进行编程式导航。以下是具体实现方法: 使用浏览器API met…

vue实现试卷

vue实现试卷

Vue实现试卷系统的基本思路 使用Vue.js构建试卷系统需要结合组件化开发、状态管理和后端数据交互。核心功能包括题目展示、答题逻辑、计时器和提交答案。 核心功能模块划分 试卷组件结构 试卷容…

vue原理实现

vue原理实现

Vue 原理实现的核心机制 Vue.js 的核心原理基于响应式系统、虚拟 DOM 和模板编译。以下是其核心实现机制的分解: 响应式系统 Vue 使用 Object.defineProperty(Vu…