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 = "";
Client = new XMLHttpRequest();
            if (Client) {
                Client.onreadystatechange = function () {
                    readyStateCallBack(Client, url);
      "GET", url, true);
                Client.responseType = "blob";

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


No comments:

Post a Comment