javascriptjquery.netashxgeneric-handler

Javascript Download file using ashx


I need create a JS method that calls a Generic Handler (ashx) that returns a file (byte array). This file can be a xml, txt or Pdf. I resolve my problem using the code below, but when the file doesn't exists, I'm redirected to another page with error message (or 404 if I config it in ashx), but I want just show a alert message to user with the error. How can I do that?

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

Solution

  • I advise you to use ajax instead of redirecting your window. Send a HEAD HTTP method to check if a file exists (without downloading it obviously.) and based on that decide what to do.

    function urlExists(url)
    {
        var http = new XMLHttpRequest();
        http.open('HEAD', url, false);
        http.send();
        return http.status!=404;
    }
    

    Based on that simple function perform a simple check:

    var urlToDownload = "MyHandler.ashx?parameter1=" + idAction + "&parameter2=" + fileType + "&parameter3=" + chave;
    
    if(urlExists(urlToDownload)){
        window.location = urlToDownload;
    } else {
        alert('File not exists.');
    }
    

    My answer is based on an answer here: How do I check if file exists in jQuery or JavaScript?