Javascript 使用 ashx 下载文件

Javascript Download file using ashx

我需要创建一个调用通用处理程序 (ashx) 的 JS 方法 即 returns 一个文件(字节数组)。此文件可以是 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();
}

我建议您使用 ajax 而不是重定向您的 window。 发送一个 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?