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'); ?>
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>
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!