我想直接在浏览器中查看PDF
文件。我知道这个问题已被提出,但我找不到适用于我的解决方案。
到目前为止,这是我的动作控制器代码:
public ActionResult GetPdf(string fileName)
{
string filePath = "~/Content/files/" + fileName;
return File(filePath, "application/pdf", fileName);
}
以下是我的观点:
@{
doc = "Mode_d'emploi.pdf";
}
<p>@Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)</p>
当我鼠标悬停时,此处的链接是链接:
我的代码存在的问题是浏览器中未查看pdf
文件,但收到一条消息,询问我是否打开或保存文件。
我知道这是可能的,我的浏览器支持它,因为我已经使用其他网站对其进行了测试,允许我直接在浏览器中查看pdf
。
例如,这是我鼠标悬停链接(在另一个网站上)时的链接:
正如您所看到的,生成的链接存在差异。我不知道这是否有用。
任何想法如何直接在浏览器中查看我的pdf
?
答案 0 :(得分:37)
接受的答案是错误的。您收到要求您打开或保存文件的消息的原因是您要指定文件名。如果您未指定文件名,则将在浏览器中打开PDF文件。
所以,您需要做的就是将行动改为:
public ActionResult GetPdf(string fileName)
{
string filePath = "~/Content/files/" + fileName;
return File(filePath, "application/pdf");
}
或者,如果您需要指定文件名,您必须这样做:
public ActionResult GetPdf(string fileName)
{
string filePath = "~/Content/files/" + fileName;
Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
return File(filePath, "application/pdf");
}
答案 1 :(得分:18)
尝试返回File
FileStreamResult
public ActionResult GetPdf(string fileName)
{
var fileStream = new FileStream("~/Content/files/" + fileName,
FileMode.Open,
FileAccess.Read
);
var fsResult = new FileStreamResult(fileStream, "application/pdf");
return fsResult;
}
答案 2 :(得分:12)
将您的代码更改为:
Response.AppendHeader("Content-Disposition","inline;filename=xxxx.pdf");
return File(filePath, "application/pdf");
答案 3 :(得分:1)
如果您读取存储在数据库映像列中的文件,则可以像这样使用:
public ActionResult DownloadFile(int id)
{
using (var db = new DbContext())
{
var data =
db.Documents.FirstOrDefault(m => m.ID == id);
if (data == null) return HttpNotFound();
Response.AppendHeader("content-disposition", "inline; filename=filename.pdf");
return new FileStreamResult(new MemoryStream(data.Fisier.ToArray()), "application/pdf");
}
}
答案 4 :(得分:0)
如果您使用 Rotativa 包生成PDF,请不要使用 FileName 属性为文件添加名称,如下例所示。
return new PartialViewAsPdf("_JcPdfGenerator", pdfModel);
希望这对某人有帮助。
答案 5 :(得分:0)
是的,只需重定向即可。它会像您需要的那样扩展.pdf ..
protected void OpenPdfPdf_Click(object sender, EventArgs e)
{
Response.Redirect("jun.pdf");
}
或其他方法,其打开方式类似于.aspx页面-
protected void OpenPdf_Click(object sender, EventArgs e)
{
string path = Server.MapPath("jun.pdf");
//or you want to load from url change path to
//string path="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
答案 6 :(得分:-1)
尽管以前的帖子通常是正确的;我认为其中大多数不是最佳做法!
我建议将操作返回类型更改为FileContentResult
,并在操作主体末尾使用return new FileContentResult(fileContent, "application/pdf");
。