首頁  >  文章  >  web前端  >  如何追蹤 XMLHttpRequest 操作的進度,尤其是大檔案上傳和下載?

如何追蹤 XMLHttpRequest 操作的進度,尤其是大檔案上傳和下載?

Barbara Streisand
Barbara Streisand原創
2024-10-28 02:05:30445瀏覽

How can I track the progress of XMLHttpRequest operations, especially for large file uploads and downloads?

監控XMLHttpRequest 進度:綜合指南

標準XMLHttpRequest (XHR) API 缺乏對進度追蹤的內建支持,阻礙了在大檔案上傳時顯示進度條的努力上傳。但是,許多瀏覽器提供非標準擴充來啟用進度監控。

上傳的位元組數

要監控上傳位元組的進度,請利用 xhr.upload.onprogress 事件。瀏覽器知道正在上傳的檔案的大小和已傳輸的資料量,從而可以確定上傳進度。

下載的位元組數

確定下載位元組的進度(使用xhr.responseText 時)更加複雜,因為瀏覽器事先不知道正在傳輸的資料的總大小。一種解決方案是在伺服器腳本中設定 Content-Length 標頭來指定預期的總位元組大小。

例如,如果我們的伺服器腳本讀取5 秒的ZIP 文件,我們可以如下設定標頭:

<code class="php">$filesize = filesize('test.zip');
header("Content-Length: " . $filesize); // Set header length
readfile('test.zip');
exit 0;</code>

透過設定header,瀏覽器可以決定回應的總長度並相應地監控接收到的位元組。

事件監控

要監控上傳和下載的進度,請使用以下事件偵聽器:

<code class="javascript">// Event listener for upload progress
xhr.upload.onprogress = function(evt) {
  if (evt.lengthComputable) {
    var uploadPercentage = (evt.loaded / evt.total) * 100;
    // Update progress bar or display percentage
  }
};

// Event listener for download progress
xhr.onprogress = function(evt) {
  if (evt.lengthComputable) {
    var downloadPercentage = (evt.loaded / evt.total) * 100;
    // Update progress bar or display percentage
  }
};</code>

範例

此範例示範了使用以下方法在檔案下載期間監控進度: jQuery UI 的進度條:

<code class="javascript">function updateProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = (evt.loaded / evt.total) * 100;
    $('#progressbar').progressbar("option", "value", percentComplete);
  }
}

function sendRequest() {
  var req = new XMLHttpRequest();
  $('#progressbar').progressbar();
  req.onprogress = updateProgress;
  req.onloadstart = function() {
    updateProgress({ loaded: 0, total: 0 });
  };
  req.open('GET', 'test.php', true);
  req.send();
}

// Sending the request
sendRequest();</code>

透過結合這些技術,您可以有效監控XMLHttpRequest 操作的進度,從而在大文件傳輸時實現更人性化的體驗。

以上是如何追蹤 XMLHttpRequest 操作的進度,尤其是大檔案上傳和下載?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn