当前位置:首页 > VUE

vue前端实现下载进度

2026-01-12 07:49:57VUE

Vue 前端实现下载进度的方法

使用 axios 的 onDownloadProgress 回调

在 axios 请求中,可以通过 onDownloadProgress 回调函数实时获取下载进度。该回调会提供一个事件对象,包含 loaded(已下载字节)和 total(总字节)属性。

axios.get('/file-url', {
  responseType: 'blob',
  onDownloadProgress: (progressEvent) => {
    const percentCompleted = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
    console.log(percentCompleted + '%');
  }
}).then(response => {
  // 处理下载完成后的逻辑
});

结合 Vue 的响应式数据更新进度条

将进度数据绑定到 Vue 的 data 中,通过模板或计算属性实时显示进度条。

export default {
  data() {
    return {
      downloadProgress: 0
    };
  },
  methods: {
    downloadFile() {
      axios.get('/file-url', {
        responseType: 'blob',
        onDownloadProgress: (progressEvent) => {
          this.downloadProgress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
        }
      }).then(response => {
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'filename.ext');
        document.body.appendChild(link);
        link.click();
      });
    }
  }
};

使用进度条组件

结合 UI 框架(如 Element UI、Ant Design Vue)的进度条组件,实现可视化效果。

<template>
  <div>
    <el-progress :percentage="downloadProgress"></el-progress>
    <button @click="downloadFile">下载文件</button>
  </div>
</template>

处理跨域和分块下载

对于大文件或分块下载,需确保服务器支持 Content-Length 头信息。若服务器未返回 total,需手动计算或分块处理。

onDownloadProgress: (progressEvent) => {
  if (progressEvent.lengthComputable) {
    this.downloadProgress = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
  } else {
    // 无法计算总大小时的备选方案
    this.downloadProgress = Math.round(
      (progressEvent.loaded / estimatedTotal) * 100
    );
  }
}

使用 Fetch API 替代方案

若未使用 axios,可通过 Fetch API 的 ReadableStream 实现类似功能。

vue前端实现下载进度

fetch('/file-url')
  .then(response => {
    const reader = response.body.getReader();
    const contentLength = +response.headers.get('Content-Length');
    let receivedLength = 0;

    return new Promise((resolve) => {
      function processChunk({ done, value }) {
        if (done) {
          resolve(new Blob([chunks]));
          return;
        }
        chunks.push(value);
        receivedLength += value.length;
        this.downloadProgress = Math.round((receivedLength / contentLength) * 100);
        return reader.read().then(processChunk);
      }
      return reader.read().then(processChunk);
    });
  });

注意事项

  • 确保服务器正确返回 Content-Length 头,否则 total 可能为 0。
  • 进度计算需处理 lengthComputablefalse 的情况。
  • 大文件下载建议使用分块或流式处理,避免内存问题。

标签: 进度vue
分享给朋友:

相关文章

vue实现弹窗

vue实现弹窗

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

vue实现建模

vue实现建模

Vue 实现建模的方法 在 Vue 中实现建模通常涉及数据绑定、组件化和状态管理。以下是几种常见的方法: 数据驱动建模 Vue 的核心是数据驱动视图。通过定义数据模型,Vue 会自动更新 DOM。例…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FFm…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutati…

vue动画实现

vue动画实现

Vue动画实现方法 Vue提供了多种方式实现动画效果,主要通过内置组件和第三方库完成。 使用<transition>组件 Vue内置的<transition>组件可以为元素添…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…