c# - PDF 文件未在 .aspx 页面上下载为 pdf
问题描述
所以我有一个使用此代码预览 PDF 文件的代码:
System.Net.WebClient client = new System.Net.WebClient();
//text box holds the path to the original pdf file in a folder
Byte[] Thisbuffer = client.DownloadData(TextBox.Text);
if (Thisbuffer!= null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", Thisbuffer.Length.ToString());
Response.BinaryWrite(Thisbuffer);
}
当我使用以下选项进行下载时,它可以在 chrome、IE 和 Edge 中查看 PDF 文件,但在 chrome 上查看:
它将文件下载为 .aspx 而不是 .pdf。这仅在 chrome 中发生,而不在 IE 或 Edge 中发生。
我试过Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf");
了,这个自动下载的文件不允许它在下载前查看。任何帮助表示感谢谢谢!
解决方案
Chrome 的内置 PDF 查看器下载按钮指向 PDF 的原始 URL,因此在您的情况下是 aspx 页面。此问题的一个潜在解决方案是创建一个新的 aspx 页面,该页面在 page_load 上加载 PDF,然后以新页面为目标。
不确定您的原始代码块是如何被调用的,但您应该能够插入带有<a>
锚标记的目标页面或使用Response.Redirect()
.
目标页面加载示例:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["RequestedPath"] != null)
{
System.Net.WebClient client = new System.Net.WebClient();
//text box holds the path to the original pdf file in a folder
Byte[] Thisbuffer = client.DownloadData(Request.QueryString["RequestedPath"]);
if (Thisbuffer!= null)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=myPDFfile.pdf");
HttpContext.Current.Response.AddHeader("content-length", Thisbuffer.Length.ToString());
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.BinaryWrite(Thisbuffer);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
推荐阅读
- c - 关闭后如何在c中存储变量的值
- c# - 通过 MS Teams Bot 中的主动私人消息对用户进行身份验证
- javascript - 如何从 firebase 获取用户的 uid?
- javascript - 当 Content == "0" 使用 JQuery 时隐藏 Div?
- android - Room - 使用 @get:Query 代替 @Query
- android - 当我使用 User-ID 进行跨平台数据分析时,为什么自定义事件报告失败?
- javascript - 如何将 javascript 函数简化为干净可读的代码?
- c++ - 优先队列函数比较
- jenkins - 重建 jenkins 作业而不进行更改显示失败状态
- python - Google colab - 有没有办法在会话期间记录峰值 RAM?