2011-08-18 90 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);