2017-05-30 87 views
1

如果我直接从我的程序中生成PDF的网址直接下载。AJAX-Post文件未下载后

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) 
    { 

    } 
} 

但是,如果我做了一个POST与我的JSON的URL这个方法不给我一个直接的下载。

带JSON字符串的POST是成功的。但是,下载不会在Ajax-Call之后启动。我的程序是一个简单的ASPX网站,通过Page_Load-Event加载所有数据和功能。去这个

回答

1

一种方法是打AJAX POST和呼叫的成功返回文件的下载链接,然后在浏览器重定向到该链接下载文件,就像这样:

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

非常有用回答!但是,我可以将其更改为直接下载,而不是在我的浏览器中打开PDF? – Cobi

+0

@PeterH不幸的。你不能直接使用AJAX下载文件。 –

+0

@PeterH你可以查看http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/ –