Home > Web Front-end > JS Tutorial > How Can I Track the Progress of Data Transfer in XMLHttpRequest?

How Can I Track the Progress of Data Transfer in XMLHttpRequest?

Patricia Arquette
Release: 2024-10-29 10:02:02
Original
426 people have browsed it

How Can I Track the Progress of Data Transfer in XMLHttpRequest?

Monitoring Progress in XMLHttpRequest

XMLHttpRequest allows web applications to send and receive data asynchronously. Is it possible to track the progress of an XMLHttpRequest, specifically the bytes uploaded and downloaded?

Bytes Uploaded

Getting the progress of bytes uploaded is relatively straightforward. Utilize the xhr.upload.onprogress event. The browser calculates the progress by comparing the uploaded data size to the total file size.

Bytes Downloaded

Monitoring the progress of bytes downloaded is more challenging as the browser typically doesn't know the total response size. A workaround involves setting the Content-Length header on the server-side script to indicate the total response size. This enables the browser to calculate the download progress.

Example

Consider a server script that reads and sends a zip file with a known size:

<?php
$filesize = filesize('test.zip');
header("Content-Length: " . $filesize);
readfile('test.zip');
?>
Copy after login

The JavaScript code below can then monitor the download progress using the Content-Length header:

<code class="javascript">function updateProgress(evt) {
   if (evt.lengthComputable) {
      // evt.loaded: Bytes received by the browser
      // evt.total: Total bytes specified in the header
      var percentComplete = (evt.loaded / evt.total) * 100;
      $('#progressbar').progressbar("option", "value", percentComplete);
   }
}   
function sendreq(evt) {
    var req = new XMLHttpRequest(); 
    $('#progressbar').progressbar();    
    req.onprogress = updateProgress;
    req.open('GET', 'test.php', true);  
    req.onreadystatechange = function (aEvt) {  
        if (req.readyState == 4) 
        {  
             //run any callback here
        }  
    };  
    req.send(); 
}</code>
Copy after login

This solution allows you to monitor the download progress even for large files where polling the server for updates is not ideal.

The above is the detailed content of How Can I Track the Progress of Data Transfer in XMLHttpRequest?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template