当前位置:首页 > 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实现流程

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

vue拖拽实现

vue拖拽实现

Vue 拖拽实现方法 使用 HTML5 原生拖拽 API HTML5 提供了原生拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 drop 事…

vue实现购票

vue实现购票

Vue 实现购票功能 数据结构设计 购票功能通常需要以下数据结构: 场次信息(时间、地点、价格) 座位信息(可选座位、已售座位) 用户订单信息 示例数据结构: data() { return…

vue实现popper

vue实现popper

Vue 实现 Popper 的方法 使用 Tippy.js 库 Tippy.js 是一个轻量级的 Popper.js 封装库,提供丰富的工具提示功能。安装 Tippy.js 及其 Vue 封装: n…

vue实现分站

vue实现分站

Vue 实现分站的方案 在 Vue 中实现分站功能通常涉及路由配置、环境变量管理和动态加载资源。以下是几种常见的实现方式: 基于路由的分站实现 通过 Vue Router 配置多路由,区分不同站点的…

vue实现settimeout

vue实现settimeout

在 Vue 中实现 setTimeout Vue 中可以通过 JavaScript 原生的 setTimeout 方法实现延时操作,但需要注意结合 Vue 的响应式特性和生命周期管理。以下是几种常见实…