从ASHX返回PDF与网页 [英] Return PDF to WebPage from ASHX

查看:356
本文介绍了从ASHX返回PDF与网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a web page with a "download" link on it.

使用jQuery我做一个Ajax得到一个ASHX文件。

Using jQuery I do an Ajax Get to a ASHX file.

在ASHX我得到的文件的流。我再流转换为字节数组,并返回字节数组回调用HTML页面;

In the ASHX I get the Stream of the file. I then convert the stream to a byte array and return the byte array back to the calling html page;

jQuery的

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

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

});



C#

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不会显示在屏幕上。

I don't get an error but also the PDF doesn't display on screen.

在理想情况下,我想的PDF回来了jQuery来在浏览器中一个单独的选项卡启动PDF。

Ideally I'd like the pdf returned and the jQuery to launch the pdf in a seperate tab within the browser.

我怎样才能做到这一点还是我究竟做错了什么?

How can I make this happen or what am I doing wrong?

推荐答案

试试这个(不要使用 。获得):

Try this (do not use .get):

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

要防止文件不以'%开始PDF的错误,使用 Response.BinaryWrite

To prevent the "File does not begin with '%PDF" error, use 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();   

这篇关于从ASHX返回PDF与网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆