Tuesday, June 5, 2012

How to get progress from XMLHttpRequest


Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)?



This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded.



note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.


Source: Tips4all

8 comments:

  1. For the bytes uploaded is quite easy. Just monitor the xhr.upload.onprogress event, browser know the size of the files has to upload and the size of uploaded data so it can give the progress info.

    For the bytes downloaded (when get info with the xhr.responseText), it's a little more difficult, because the browser doesn't know how many bytes with send the server process. The only thing that browser knows in this case is the size of bytes it's receiving. But there is a solution for this, it's sufficient to set an estimated headers length on the server script so to give the size of bytes the browser is receiving. for more info go to https://developer.mozilla.org/en/Using_XMLHttpRequest .

    Example:
    My server script reads a zip file (it takes 5 seconds):

    $filesize=filesize('test.zip');

    header("Content-Length: ".$filesize);//set header length
    //if the headers it not set then the evt.loaded will be 0
    readfile('test.zip');
    echo "asdasd";


    Now i can monitor the download process of the server script beacause i know it's total length:

    function updateProgress(evt)
    {
    if (evt.lengthComputable)
    { //evt.loaded the bytes browser receive
    //evt.total the total bytes seted 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)
    {

    }
    };
    req.send();
    }

    ReplyDelete
  2. There's a nice discussion of the Progress Indicator for AJAX pattern here:

    http://ajaxpatterns.org/Progress_Indicator

    One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.

    ReplyDelete
  3. For the total uploaded there doesn't seem to be a way to handle that, but there's something similar to what you want for download. Once readyState is 3, you can periodically query responseText to get all the content downloaded so far as a String (this doesn't work in IE), up until all of it is available at which point it will transition to readyState 4. The total bytes downloaded at any given time will be equal to the total bytes in the string stored in responseText.

    For a all or nothing approach to the upload question, since you have to pass a string for upload (and it's possible to determine the total bytes of that) the total bytes sent for readyState 0 and 1 will be 0, and the total for readyState 2 will be the total bytes in the string you passed in. The total bytes both sent and received in readyState 3 and 4 will be the sum of the bytes in the original string plus the total bytes in responseText.

    ReplyDelete
  4. Firefox 3.5 will support upload progress event

    ReplyDelete
  5. Firefox supports XHR download progress events.

    ReplyDelete
  6. If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).

    Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).

    There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).

    ReplyDelete
  7. One solution is still possible without any browser support:


    Divide your file into, say, 10 chunks.
    Make AJAX uploads of all those chunks sequentially (using callbacks).
    So progress bar could be implemented quite straightforwardly.


    /joke

    ReplyDelete
  8. The only way to do that with pure javascript is to implement some kind of polling mechanism.
    You will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.

    A more efficient way would be to use flash. The flex component FileReference dispatchs periodically a 'progress' event holding the number of bytes already uploaded.
    If you need to stick with javascript, bridges are available between actionscript and javascript.
    The good news is that this work has been already done for you :)

    swfupload

    This library allows to register a javascript handler on the flash progress event.

    This solution has the hudge advantage of not requiring aditionnal resources on the server side.

    ReplyDelete