Thursday, February 23, 2012

XMLHttpRequest get url of request

Problem: When downloading files with xhr (xml http request) we need to set a callback to the onreadystatechange property, which does not allow sending arguments such as the current url being downloaded (which also can't be retrieved from the xhr instance). This is usually an issue when downloading multiple files, and specially when we want to maintain the file names.

Solution: Use "closures" by immediately defining the function on the onreadystatechange property and calling a method inside it, instead of using a callback (e.g. onreadystatechange=mycallback; ).

string url = "http://myurl.com/myfile.extension";
Client = new XMLHttpRequest();
            if (Client) {
                Client.onreadystatechange = function () {
                    readyStateCallBack(Client, url);
                };
                Client.open("GET", url, true);
                Client.responseType = "blob";
                Client.send(null);
}

function readyStateCallBack(Client, url) {
    //download file
    if (Client.readyState === 4) {
        if (Client.status !== 200) {
            asyncError("Unable to download blob - status code: " + Client.status.toString());
        } else {
            var file = Client.response;
            var fileName = url.toString().replace(/http:\/\/.*\//i, '');
            //todo: copy the file somewhere
        }
    }
}

sources:
http://stackoverflow.com/questions/7945781/clarification-on-closures-in-javascript-with-ajax
http://stackoverflow.com/questions/4674021/xhr-get-request-url-in-onreadystatechange

No comments:

Post a Comment