在AJAX-Post之后,文件未下载

时间:2017-05-30 07:21:15

标签: javascript c# asp.net json ajax

如果我直接从我的程序中生成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加载所有数据和功能。

1 个答案:

答案 0 :(得分:1)

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

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