Download file via ashx

Asked

Viewed 77 times

1

I need to make a Javascript method that calls an ashx (Generic Handler) that returns an array of bytes (a file). This file can be XML, TXT or PDF. So far I solved the problem, but when the file does not exist, I am redirected to another page, but I just want to display an Alert with the error message.

function GetFile(idAction, chave, fileType) {
    window.downloadfile = function (e) {
        window.location = "MyHandler.ashx?parameter1="
            + idAction + "&parameter2=" + fileType + "&parameter3=" + chave;
    }
    downloadfile();
}

1 answer

1


I solved my problem with the following code:

function GetFile(p1, p2, p3) {
    ShowLoadDiv();
    setTimeout(function () {
        var url = "/MyHandler.ashx?p1=" + p1;
        if (GetRequestReturnStatus(url)) {
            window.open(url);
        }
        HideLoadDiv();
    }, 500);
}

function GetRequestReturnStatus(url) {
    var http = new XMLHttpRequest();

    http.open('HEAD', url, false);
    http.send();   

    if (http.status == 404 || http.status == 403 || http.status == 500) {        
        ShowMessage("nFailure", "some error message");
        return false;
    }
    return true;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.