React和Vue怎么实现文件下载进度条

发布时间:2023-04-26 17:17:24 作者:iii
来源:亿速云 阅读:172

React和Vue怎么实现文件下载进度条

在现代Web应用中,文件下载是一个常见的需求。为了提高用户体验,显示文件下载的进度条是一个很好的做法。本文将介绍如何在React和Vue中实现文件下载进度条。

1. 使用React实现文件下载进度条

在React中,我们可以使用XMLHttpRequestfetch API来下载文件,并通过监听progress事件来获取下载进度。

1.1 使用XMLHttpRequest

import React, { useState } from 'react';

const FileDownloader = () => {
  const [progress, setProgress] = useState(0);

  const downloadFile = () => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://example.com/file.zip', true);
    xhr.responseType = 'blob';

    xhr.onprogress = (event) => {
      if (event.lengthComputable) {
        const percentComplete = (event.loaded / event.total) * 100;
        setProgress(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 = 'file.zip';
        link.click();
      }
    };

    xhr.send();
  };

  return (
    <div>
      <button onClick={downloadFile}>Download File</button>
      <div>Progress: {progress.toFixed(2)}%</div>
    </div>
  );
};

export default FileDownloader;

1.2 使用fetch API

import React, { useState } from 'react';

const FileDownloader = () => {
  const [progress, setProgress] = useState(0);

  const downloadFile = async () => {
    const response = await fetch('https://example.com/file.zip');
    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;
      setProgress((receivedLength / contentLength) * 100);
    }

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

  return (
    <div>
      <button onClick={downloadFile}>Download File</button>
      <div>Progress: {progress.toFixed(2)}%</div>
    </div>
  );
};

export default FileDownloader;

2. 使用Vue实现文件下载进度条

在Vue中,我们同样可以使用XMLHttpRequestfetch API来实现文件下载进度条。

2.1 使用XMLHttpRequest

<template>
  <div>
    <button @click="downloadFile">Download File</button>
    <div>Progress: {{ progress.toFixed(2) }}%</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      progress: 0,
    };
  },
  methods: {
    downloadFile() {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', 'https://example.com/file.zip', true);
      xhr.responseType = 'blob';

      xhr.onprogress = (event) => {
        if (event.lengthComputable) {
          const percentComplete = (event.loaded / event.total) * 100;
          this.progress = 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 = 'file.zip';
          link.click();
        }
      };

      xhr.send();
    },
  },
};
</script>

2.2 使用fetch API

<template>
  <div>
    <button @click="downloadFile">Download File</button>
    <div>Progress: {{ progress.toFixed(2) }}%</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      progress: 0,
    };
  },
  methods: {
    async downloadFile() {
      const response = await fetch('https://example.com/file.zip');
      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.progress = (receivedLength / contentLength) * 100;
      }

      const blob = new Blob(chunks);
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = 'file.zip';
      link.click();
    },
  },
};
</script>

3. 总结

无论是React还是Vue,实现文件下载进度条的核心思想都是通过监听下载过程中的progress事件来更新进度条的状态。我们可以使用XMLHttpRequestfetch API来实现这一功能。根据项目的具体需求,选择合适的方式来实现文件下载进度条,可以显著提升用户体验。

推荐阅读:
  1. 如何在React中引入Antd组件
  2. React+TypeScript怎么构建项目

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react vue

上一篇:Sentinel中冷启动限流原理WarmUpController是什么

下一篇:Spring JPA find单表查询方法怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》