当前位置:首页 > 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 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&g…

vue实现suspense

vue实现suspense

Vue 3 中实现 Suspense Suspense 是 Vue 3 引入的一个内置组件,用于处理异步依赖的加载状态。它允许在等待异步组件或异步数据加载时显示一个后备内容(fallback),直到异…

vue实现ios

vue实现ios

Vue 实现 iOS 风格应用 使用 Vue 实现 iOS 风格的应用,可以通过结合 UI 框架和自定义样式来达成目标。以下是具体方法和步骤: 选择 iOS 风格的 UI 框架 Vue 生态中有多…

vue实现layout

vue实现layout

Vue 实现 Layout 布局的方法 在 Vue 中实现 Layout 布局通常涉及路由嵌套、组件化设计和动态渲染。以下是几种常见的实现方式: 使用嵌套路由 通过 Vue Router 的嵌套路由…

实现vue vm

实现vue vm

Vue VM 实现方法 Vue VM(ViewModel)是 Vue.js 的核心概念之一,负责连接视图(View)和数据模型(Model)。以下是实现 Vue VM 的几种方法: 使用 Vue 实…

vue实现部门树

vue实现部门树

Vue 实现部门树的方法 使用递归组件实现树形结构 递归组件是 Vue 中实现树形结构的常见方式。通过组件自身调用自身,可以轻松构建多层级的部门树。 <template> <d…