当前位置:首页 > 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中实现元素的显示和隐藏可以通过多种方式完成,以下是常见的几种方法: 1. 使用v-if指令v-if根据条件动态添加或移除DOM元素,适合需要频繁切换的场景。当条件为fa…

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue核心实现

vue核心实现

Vue 核心实现原理 Vue.js 的核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是关键实现原理的详细说明: 响应式系统 Vue 使用 Object.defineProper…

vue底部实现

vue底部实现

Vue 底部实现方法 在 Vue 项目中实现底部布局可以通过多种方式完成,以下是一些常见的方法: 使用固定定位 将底部元素固定在页面底部,适用于单页应用或需要始终显示的底部栏。 <temp…

vue 实现$(id)

vue 实现$(id)

在 Vue 中实现类似 jQuery 的 $(id) 功能,可以通过以下几种方式操作 DOM 元素: 使用 ref 属性 Vue 推荐使用 ref 属性来直接访问 DOM 元素或组件实例。在模板中为…