XMLHttpRequest (XHR) provides a mechanism for performing asynchronous requests from JavaScript. While it offers support for tracking the upload progress using the xhr.upload.onprogress event, obtaining the progress of downloads is not as straightforward due to the lack of information about the total bytes to be received.
Getting the upload progress is relatively simple. The browser maintains information about the size of the file being uploaded and the amount of data transferred, making it possible to derive the progress through the xhr.upload.onprogress event.
For downloads, the challenge arises from the browser's inability to know the size of the incoming data. However, this can be overcome by setting a Content-Length header in the server response, which specifies the total size of the data to be transferred.
The server-side code responsible for delivering the content should set the Content-Length header based on the size of the file or data being downloaded. Example:
$filesize = filesize('test.zip'); header("Content-Length: " . $filesize); // Set header length readfile('test.zip'); exit 0;
With the Content-Length header set, the client-side code can now track the download progress:
function updateProgress(evt) { if (evt.lengthComputable) { // evt.loaded: Bytes received by the browser // evt.total: Total bytes defined by 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) { // Callback actions here } }; req.send(); }
This code creates a progress bar using the jQuery UI library, showing the progress percentage as the data is received. By leveraging the Content-Length header, the browser can accurately calculate and display the download progress, making it useful for large file downloads where a visual progress indicator is desired.
The above is the detailed content of How do you track download progress in XMLHttpRequest without knowing the total file size?. For more information, please follow other related articles on the PHP Chinese website!