当前位置:首页 > VUE

vue前端实现下载进度

2026-02-09 20:55:00VUE

实现下载进度显示的方法

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

使用XMLHttpRequest实现

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

vue前端实现下载进度

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配置项实现:

vue前端实现下载进度

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模板中可以这样显示进度:

<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 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue实现hover

vue实现hover

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

vue实现suspense

vue实现suspense

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

vue实现treeselect

vue实现treeselect

Vue TreeSelect 实现方法 使用 Vue 实现 TreeSelect 组件可以通过以下几种方式完成,包括使用现成的第三方库或自行封装组件。 使用第三方库 推荐使用成熟的第三方 TreeS…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

vue实现分栏

vue实现分栏

Vue实现分栏的常见方法 使用CSS Flexbox布局 通过Flexbox可以快速实现分栏效果,适合大多数响应式布局场景 <template> <div class="con…