2011-08-18 91 views
2

我有一個帶有「下載」鏈接的網頁。將ASHX的PDF返回到網頁

使用jQuery我做一個Ajax獲取一個ASHX文件。

在ASHX中,我得到了文件的流。然後,我將該流轉換爲一個字節數組,並將字節數組返回給調用的html頁面;

jQuery的

$(".DownloadConvertedPDF").click(function() { 
    var bookId = $(this).attr("bookId"); 

    $.get('/UserControls/download.ashx?format=pdf&bookId=' + bookId, {}, function (data) { }); 

}); 

C#

context.Response.ContentType = "Application/pdf"; 
Stream fileStream = publishBookManager.GetFile(documentId); 
byte[] buffer = new byte[16 * 1024]; 
using (MemoryStream ms = new MemoryStream()) 
{ 
    int read; 
    while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0) 
    { 
    ms.Write(buffer, 0, read); 
    } 
} 

context.Response.OutputStream.Write(buffer, 0, buffer.Length); 

我沒有得到一個錯誤,但也PDF不會顯示在屏幕上。

理想情況下,我希望將PDF返回並使用jQuery在瀏覽器內的獨立選項卡中啓動pdf。

我該如何做到這一點或我做錯了什麼?

回答

5

試試這個(不要使用.get):

window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer"); 

爲了防止 「文件不以「%PDF開始」 的錯誤,使用Response.BinaryWrite

context.Response.Clear(); 
context.Response.ClearContent(); 
context.Response.ClearHeaders(); 
context.Response.ContentType = "application/pdf"; 

Stream fileStream = publishBookManager.GetFile(documentId); 
byte[] buffer = new byte[16 * 1024]; 
using (MemoryStream ms = new MemoryStream()) 
{ 
    int read; 
    while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0) 
    { 
    ms.Write(buffer, 0, read); 
    } 
} 

context.Response.BinaryWrite(data); 
context.Response.Flush(); 
+0

@griegs:使用'window.open'方法。我不認爲'.get'會起作用。 – Mrchief

+0

嗯,這是好得多,但我得到一個錯誤「文件不以'%PDF-'開頭 – griegs

+0

這是可怕的錯誤!請參閱我的更新 – Mrchief

0

我也使用窗口打開pdf。但它總是顯示,而嘗試通過地址欄直接使用相同的URL而不登錄。如何解決這個問題。

0

通過使用context.Response.TransmitFile的,服務於從一個ASHX網絡處理PDF文件更簡潔的方法是:

context.Response.Clear(); 
context.Response.ContentType = "application/pdf"; 
string filePath = System.Web.HttpContext.Current.Server.MapPath(@"~\path-to\your-file.pdf"); 
context.Response.TransmitFile(filePath);