我在这里指定了非常相似的要求.
我需要让用户的浏览器手动开始下载 $('a#someID').click();
但我无法使用该window.href方法,因为它将当前页面内容替换为您尝试下载的文件.
相反,我想在新窗口/选项卡中打开下载.这怎么可能?
我正在从主页客户端脚本(Jquery)请求.ashx页面,该脚本具有下载PDF文件的代码.当我调试它时,我可以看到执行"文件下载"代码,但文件没有下载.
$.ajax({
type: "POST",
url: "FileDownload.ashx",
dataType: "html",
success: function (data) { }
}
);
public class FileDownload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string fileName = "BUSProjectCard.pdf";
string filePath = context.Server.MapPath("~/Print/");
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
context.Response.TransmitFile(filePath + fileName);
context.Response.End();
}
Run Code Online (Sandbox Code Playgroud) 我有一个网页,用户可以通过ASP.NET Web处理程序(.ashx)下载PDF文件.它的实现就像这个问题的答案一样.我遇到的问题是当我window.top.location.href = url;在我的JavaScript中执行此操作时,如果处理程序中抛出异常,我无法真正控制会发生什么.当一切正常时,用户体验是他们基本上停留在他们所在的页面上,并且浏览器告诉他们他们可以下载PDF文件.但是,当处理程序中抛出异常时,它们会被重定向到处理程序的URL并显示一个空白页面.
以下是一些示例代码,使其更加清晰:
JavaScript的:
function openPDF() {
var url = GeneratePDFUrl();
window.top.location.href = url;
}
Run Code Online (Sandbox Code Playgroud)
处理器:
public override void Process(HttpContext context)
{
byte[] pdfdata = GetPDFData();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + GetPDFFileName() + "\"");
context.Response.AddHeader("content-length", pdfdata.Length.ToString());
context.Response.BinaryWrite(pdfdata);
}
Run Code Online (Sandbox Code Playgroud)
GetPDFData()抛出异常时会发生此问题.我们正在尽我们所能阻止GetPDFData()抛出异常,但它是从用户输入生成的,所以我们也在这里处理它,以防有时我们不能/无法预测哪些会产生错误.
这是我提出的一个解决方案,但它显示了用户错误文本(而不是空白页)
public override void Process(HttpContext context)
{
try
{
byte[] pdfdata = GetPDFData();
WritePDF(pdfdata, GetPDFFileName()); // Executes code in example above
}
catch (Exception e)
{
context.Response.Clear();
context.Response.Write(GetErrorMessage(e));
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想向用户显示一个弹出窗口,以便他们留在他们所在的页面上.