如何直接在浏览器中打开pdf文件?
我想直接在浏览器中查看PDF
文件。 我知道这个问题已被提出,但我找不到适用于我的解决方案。
到目前为止,这是我的动作控制器代码:
public ActionResult GetPdf(string fileName) { string filePath = "~/Content/files/" + fileName; return File(filePath, "application/pdf", fileName); }
这是我的观点:
@{ doc = "Mode_d'emploi.pdf"; } @Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)
当我鼠标hover时,这里的链接是链接:
我的代码的问题是pdf
文件没有在浏览器中查看,但我收到一条消息,询问我是否打开或保存文件。
我知道这是可能的,我的浏览器支持它,因为我已经用另一个网站测试它,允许我直接在我的浏览器中查看pdf
。
例如,这是我鼠标hover链接(在另一个网站上)时的链接:
如您所见,生成的链接存在差异。 我不知道这是否有用。
知道如何直接在浏览器中查看我的pdf
?
而不是返回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; }
接受的答案是错误的。 您收到要求您打开或保存文件的消息的原因是您指定了文件名。 如果未指定文件名,则将在浏览器中打开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"); }
将您的代码更改为:
Response.AppendHeader("Content-Disposition","inline;filename=xxxx.pdf"); return File(filePath, "application/pdf");
如果您读取存储在数据库映像列中的文件,则可以使用如下所示:
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"); } }
如果您使用Rotativa包生成PDF,那么请不要将名称放在FileName属性文件中,如下例所示。
return new PartialViewAsPdf("_JcPdfGenerator", pdfModel);
希望这对某人有帮助。
虽然之前的post通常是正确的; 我认为大多数都不是最好的做法! 我想建议将操作返回类型更改为FileContentResult
并使用return new FileContentResult(fileContent, "application/pdf");
在行动结束时。