如何直接在浏览器中打开pdf文件?

Bro*_*ato 19 c# asp.net-mvc

我想PDF直接在浏览器中查看文件.我知道这个问题已经被问到了,但我找不到适用于我的解决方案.

到目前为止,这是我的动作控制器代码:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf", fileName);
}
Run Code Online (Sandbox Code Playgroud)

这是我的观点:

@{
   doc = "Mode_d'emploi.pdf";
} 

<p>@Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)</p>
Run Code Online (Sandbox Code Playgroud)

当我鼠标悬停时,这里的链接是链接:

在此输入图像描述

我的代码的问题是pdf文件没有在浏览器中查看,但我收到一条消息,询问我是否打开或保存文件.

在此输入图像描述

我知道这是可能的,我的浏览器支持它,因为我已经用另一个网站测试它,允许我pdf直接在我的浏览器中查看.

例如,这是我鼠标悬停链接(在另一个网站上)时的链接:

在此输入图像描述

如您所见,生成的链接存在差异.我不知道这是否有用.

知道怎样才能pdf直接在浏览器中查看我的内容?

ata*_*ati 40

接受的答案是错误的.您收到要求您打开或保存文件的消息的原因是您指定了文件名.如果未指定文件名,则将在浏览器中打开PDF文件.

所以,您需要做的就是将您的操作更改为:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf");
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要指定文件名,则必须这样做:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);        

    return File(filePath, "application/pdf");
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说很好,谢谢ataravati. (2认同)

For*_*Two 21

而不是返回a File,尝试返回aFileStreamResult

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;
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*mir 12

将您的代码更改为:

       Response.AppendHeader("Content-Disposition","inline;filename=xxxx.pdf");
       return File(filePath, "application/pdf");
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案允许在用户想要保存文件时保留文件名.谢谢. (3认同)