从ASHX返回PDF到网页
本文关键字:网页 PDF 返回 ASHX | 更新日期: 2023-09-27 18:06:01
我有一个带有"下载"链接的网页。
使用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");
要防止"File does not begin with '%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);
我也使用窗口。打开以获取pdf。但它总是显示,而试图通过地址栏直接使用相同的URL没有登录。如何解决这个问题