溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

React和Vue怎么實現文件下載進度條

發布時間:2023-04-26 17:17:24 來源:億速云 閱讀:201 作者:iii 欄目:開發技術

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來實現這一功能。根據項目的具體需求,選擇合適的方式來實現文件下載進度條,可以顯著提升用戶體驗。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女