在ASP.NET MVC中,在同一窗口中下载PDF文件时可能会遇到无法正常工作的问题。该问题主要是由于浏览器的 PDF 阅读器插件阻止了 PDF 文件下载的原因。
解决该问题的方法之一是使用文件流来下载 PDF 文件,而不是使用 ActionResult
。下面是一个示例代码:
public ActionResult DownloadPDF()
{
string fileName = "example.pdf"; // 要下载的文件名
string filePath = Server.MapPath("~/Files/" + fileName); // 文件路径
// 读取文件的字节数组并关闭文件
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
System.IO.File.Close();
// 添加文件类型的 MIME 类型
Response.ContentType = "application/pdf";
// 在 Content-Disposition 头中添加文件名和文件大小(用于浏览器下载进度)
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "; size=" + fileBytes.Length.ToString());
// 将字节数组作为文件发送到客户端
Response.BinaryWrite(fileBytes);
// 结束响应并释放响应流
Response.End();
Response.Flush();
return new EmptyResult();
}
在上述示例中,我们使用 System.IO.File.ReadAllBytes()
方法从指定文件中创建一个字节数组,然后将该字节数组添加到响应中,以便在同一窗口中下载 PDF 文件。