Javascript使用ashx下载文件

时间:2015-12-02 19:44:49

标签: javascript jquery .net ashx generic-handler

我需要创建一个调用Generic Handler(ashx)的JS方法 返回一个文件(字节数组)。该文件可以是xml,txt或Pdf。 我使用下面的代码解决了我的问题,但是当文件不存在时, 我被重定向到另一个页面并显示错误消息(如果我在ashx中配置它,则为404), 但我想向用户显示一条警告消息并显示错误。我怎么能这样做?

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

1 个答案:

答案 0 :(得分:0)

我建议您使用ajax而不是重定向窗口。 发送一个HEAD HTTP方法来检查文件是否存在(显然没有下载)。并根据它确定要做什么。

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

基于该简单函数执行简单检查:

var urlToDownload = "MyHandler.ashx?parameter1=" + idAction + "&parameter2=" + fileType + "&parameter3=" + chave;

if(urlExists(urlToDownload)){
    window.location = urlToDownload;
} else {
    alert('File not exists.');
}

我的回答是基于这里的答案: How do I check if file exists in jQuery or JavaScript?