当前位置:首页 > VUE

vue前端实现下载进度

2026-03-06 20:47:37VUE

实现下载进度的方法

在Vue前端中实现下载进度,通常需要结合XMLHttpRequest或fetch API来监听下载进度事件。以下是几种常见的实现方式:

使用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 = (event.loaded / event.total) * 100;
      console.log(`下载进度: ${percentComplete}%`);
      // 更新Vue组件中的进度状态
      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();
}

使用fetch API和ReadableStream

fetch API本身不直接提供进度事件,但可以通过ReadableStream实现类似功能。

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

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

    chunks.push(value);
    receivedLength += value.length;
    const progress = (receivedLength / contentLength) * 100;
    console.log(`下载进度: ${progress}%`);
    this.downloadProgress = progress;
  }

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

使用axios实现下载进度

axios提供了onDownloadProgress回调函数,可以方便地获取下载进度。

axios({
  url: '/file/download',
  method: 'GET',
  responseType: 'blob',
  onDownloadProgress: (progressEvent) => {
    const percentCompleted = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
    console.log(`下载进度: ${percentCompleted}%`);
    this.downloadProgress = percentCompleted;
  }
}).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();
});

在Vue组件中显示进度条

在Vue模板中,可以使用进度条组件来直观显示下载进度。

vue前端实现下载进度

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

<script>
export default {
  data() {
    return {
      downloadProgress: 0
    }
  },
  methods: {
    // 使用上述任一方法实现下载功能
  }
}
</script>

注意事项

  • 确保服务器正确设置了Content-Length头部,否则无法计算准确的进度
  • 跨域请求可能需要服务器配置CORS头部
  • 大文件下载建议使用分块下载或断点续传技术
  • 下载完成后及时释放创建的ObjectURL,避免内存泄漏

这些方法都可以在Vue项目中实现文件下载进度显示,选择哪种方式取决于项目具体需求和使用的HTTP库。

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

相关文章

vue实现星星

vue实现星星

实现星星评分的Vue组件 使用Vue实现星星评分功能可以通过组件化方式完成,以下是一个完整的实现方案: 模板部分 <template> <div class="star-ra…

vue实现drag

vue实现drag

Vue 实现拖拽功能的方法 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来完成。以下是两种常见方法的实现方式。 使用 HTML5 拖拽…

vue实现详情

vue实现详情

Vue 实现详情页的常见方法 使用动态路由 在 Vue Router 中配置动态路由参数,通过 $route.params 获取详情 ID。示例路由配置: { path: '/detail/:i…

vue 实现过滤

vue 实现过滤

Vue 实现过滤的方法 在 Vue 中实现过滤功能可以通过多种方式完成,包括使用计算属性、自定义过滤器、第三方库等。以下是几种常见的实现方法: 使用计算属性进行过滤 计算属性是 Vue 中最常用的过…

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…

vue实现例子

vue实现例子

以下是一些常见的 Vue 实现例子,涵盖基础功能到进阶应用场景: 基础数据绑定 使用 v-model 实现双向数据绑定: <template> <div> &l…