【问题标题】:Javascript Download file using ashxJavascript 使用 ashx 下载文件
【发布时间】:2015-12-02 19:44:48
【问题描述】:

我需要创建一个调用通用处理程序 (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();
}

【问题讨论】:

    标签: javascript jquery .net ashx generic-handler


    【解决方案1】:

    我建议您使用 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?

    【讨论】:

    • 无需提及,为了使该代码正常工作,您需要将服务器配置为在文件不存在的情况下返回 404。
    • 谢谢。你帮了我很多!
    猜你喜欢
    • 2011-01-20
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2017-03-13
    • 2010-09-25
    • 2012-10-07
    相关资源
    最近更新 更多