Download file via ashx

1

I need to do 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. Until then I solved the problem, but when the file does not exist, I'm 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();
}
    
asked by anonymous 02.12.2015 / 20:35

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;
}
    
04.12.2015 / 14:29