当前位置:首页 > VUE

vue前端实现下载进度

2026-02-09 20:55:00VUE

实现下载进度显示的方法

在Vue中实现下载进度显示,可以通过监听XMLHttpRequest或fetch的progress事件来获取下载进度数据。以下是具体实现方式:

使用XMLHttpRequest实现

XMLHttpRequest对象提供了progress事件,可以监听下载进度:

downloadFile(url) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';

  xhr.addEventListener('progress', (event) => {
    if (event.lengthComputable) {
      const percentComplete = Math.round((event.loaded / event.total) * 100);
      this.downloadProgress = percentComplete;
    }
  });

  xhr.onload = () => {
    if (xhr.status === 200) {
      const blob = new Blob([xhr.response]);
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = 'filename.ext';
      link.click();
    }
  };

  xhr.send();
}

使用axios实现

axios也支持进度监听,可以通过onDownloadProgress配置项实现:

async downloadWithAxios(url) {
  try {
    const response = await axios({
      url,
      method: 'GET',
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        this.downloadProgress = percentCompleted;
      }
    });

    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();
  } catch (error) {
    console.error('Download error:', error);
  }
}

使用fetch API实现

fetch API本身不直接支持进度跟踪,但可以通过读取响应体的流来实现:

async fetchWithProgress(url) {
  const response = await fetch(url);
  const reader = response.body.getReader();
  const contentLength = +response.headers.get('Content-Length');
  let receivedLength = 0;
  const chunks = [];

  while(true) {
    const {done, value} = await reader.read();
    if(done) break;

    chunks.push(value);
    receivedLength += value.length;
    this.downloadProgress = Math.round((receivedLength / contentLength) * 100);
  }

  const blob = new Blob(chunks);
  const downloadUrl = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = 'filename.ext';
  link.click();
}

进度条UI实现

在Vue模板中可以这样显示进度:

vue前端实现下载进度

<template>
  <div>
    <button @click="downloadFile">下载文件</button>
    <div v-if="downloadProgress > 0">
      <progress :value="downloadProgress" max="100"></progress>
      <span>{{ downloadProgress }}%</span>
    </div>
  </div>
</template>

注意事项

  • 确保服务器正确设置了Content-Length头部,否则无法计算进度百分比
  • 对于大文件下载,考虑使用分块下载或断点续传技术
  • 下载完成后及时释放创建的URL对象,避免内存泄漏
  • 添加错误处理逻辑,处理网络中断等异常情况

以上方法可以根据具体需求选择使用,XMLHttpRequest和axios的实现方式相对简单,而fetch API的实现则更现代但代码量稍多。

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

相关文章

vue实现条件判断

vue实现条件判断

Vue 条件判断实现方法 Vue 提供了多种方式实现条件判断,可以根据不同场景选择合适的方式。 v-if / v-else-if / v-else 这是 Vue 中最常用的条件渲染指令,根据表达式的…

vue实现流程

vue实现流程

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

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现键盘

vue实现键盘

Vue 实现键盘功能 在Vue中实现键盘功能通常涉及监听键盘事件、处理输入以及渲染虚拟键盘界面。以下是几种常见的实现方式: 监听键盘事件 通过@keydown或@keyup指令监听键盘事件,适用于需…

vue实现hover

vue实现hover

Vue 实现 hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式实现,包括使用 CSS、Vue 指令或事件监听。以下是几种常见的方法: 使用 CSS :hover 伪类 通…

vue tab实现

vue tab实现

Vue Tab 实现方法 使用动态组件实现 Tab 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现 Ta…