【问题标题】:Return PDF to WebPage from ASHX从 ASHX 返回 PDF 到网页
【发布时间】:2011-08-18 01:20:36
【问题描述】:

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

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

我怎样才能做到这一点,或者我做错了什么?

【问题讨论】:

    标签: c#


    【解决方案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】:

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

      【讨论】:

      • @griegs:使用window.open 方法。我不认为.get 会起作用。
      • 啊,好多了,但我收到一个错误“文件不以'%PDF-'开头
      • 在我的答案中再添加几行。还要确保没有返回其他 html/字符串(ashx 也应该没有标记)
      • 对不起@mrchief,问题还是一样。我知道 pdf 在那里并且正确,ashx 除了 之外没有 html
      • 无需抱歉。正如我所说,那是 dreaded 错误。如果你用谷歌搜索它,你会看到各种各样的解决方案。 :)
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2021-04-08
        • 1970-01-01
        • 2017-03-13
        • 2012-01-13
        • 2014-04-16
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 2020-02-11
        相关资源
        最近更新 更多