从ASHX将PDF返回给WebPage

时间:2011-08-18 01:20:37

标签: c#

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

使用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。

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

3 个答案:

答案 0 :(得分: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();   

答案 1 :(得分:1)

通过使用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);

答案 2 :(得分:0)

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