2017-05-30 55 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/ –