从ASHX将PDF返回给WebPage

我有一个带有“下载”链接的网页。

使用jQuery我做一个Ajax Get到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。

我怎样才能实现这一目标或者我做错了什么?

试试这个(不要使用.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(); 

通过使用context.Response.TransmitFile,一种从ashx Web处理程序提供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); 

我也使用window.open来获取pdf。 但是在没有登录的情况下直接尝试通过地址栏使用相同的URL时总会显示。如何解决这个问题。