【问题标题】:After AJAX-Post the File is not downloadingAJAX-Post 后文件未下载
【发布时间】:2017-05-30 07:21:15
【问题描述】:

如果我直接从生成 PDF 的程序访问 URL,我会直接下载。

 public void Download(byte[] file)
{

    try
    {
        MemoryStream mstream = new MemoryStream(file);
        long dataLengthToRead = mstream.Length;
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.BufferOutput = true;
        Response.ContentType = "Application/pdf"; /// if it is text or xml
        Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test.pdf");
        Response.AddHeader("Content-Length", dataLengthToRead.ToString());
        mstream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.Close();
        HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
        HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
        HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
    }
    catch (Exception e)
    {

    }
}

但是,如果我使用我的 JSON 向 URL 进行 POST,则此方法不会给我直接下载。

带有 JSON-String 的 POST 成功。但是在 Ajax-Call 之后下载不会开始。我的程序是一个简单的 ASPX 网站,它使用 Page_Load-Event 加载所有数据和函数。

【问题讨论】:

    标签: javascript c# asp.net json ajax


    【解决方案1】:

    解决此问题的一种方法是点击 ajax POST,调用成功后返回文件下载链接,然后将浏览器重定向到该链接以下载文件,如下所示:

                $.ajax({
                    url: "THE_POST_URL",
                    method: 'POST',
                    success: function (response) { //return the download link
                         window.location.href = response;
                    },
                    error: function (e) {
                    },
                });
    

    【讨论】:

    • 非常有帮助的答案!但是我可以将其更改为直接下载而不是在浏览器中打开 PDF 吗?
    • @PeterH 不幸的是。您不能使用 AJAX 直接下载文件。
    • @PeterH 你可以查看johnculviner.com/…
    • @ShaktiPhartiyal 会回复什么??!
    • @MahmodAbuJehad 响应将来自 api / url,在这种特定情况下,它应该是下载链接
    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多