无法使用MVC在浏览器中显示PDF文件

时间:2016-03-21 15:23:38

标签: asp.net-mvc asp.net-mvc-4

我遇到一个问题,我无法在任何使用MCV的网络浏览器中显示PDF文件。 我没有收到任何错误,但只是告诉我D * PV B/ S zi

我正在使用Bootstrap,Jquery和MVC。 Bellow是显示PDF的示例代码。

    public FileResult OpenDocument(int Id)
    {
        byte[] data = lst.File; // retrieve byte from db.
        string mimeType = "application/pdf";
        if (mimeType != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", data.Length.ToString());
            //Response.BinaryWrite(data);
        }
        return File(data, mimeType);
    }

请帮帮我或建议我。 提前谢谢。

4 个答案:

答案 0 :(得分:0)

这应该这样做。

如果您希望它在浏览器窗口中打开pdf,只需删除FileDownloadName行。

    public ActionResult OpenDocument(int Id)
    {
        try
        {
            byte[] data = lst.File; // retrieve byte from db.
            string mimeType = "application/pdf";
            FileContentResult document = new FileContentResult(data, mimeType);
            document.FileDownloadName = "something.pdf";
            return document;
        }
        catch
        {
            return new EmptyResult();
        }
        return new EmptyResult();
    }

答案 1 :(得分:0)

根据您的示例,您需要将data传递给File内容结果。

public ActionResult OpenDocument(int Id)
{
    //Code that uses Id to retrieve 1st variable
    //....
    byte[] data = lst.File; // retrieve byte array from db.
    if(data!=null && data.Length > 0) {
        string mimeType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "inline; filename=" + Id + ".pdf");
        return File(data, mimeType);
    }
    return new EmptyResult();
}

答案 2 :(得分:0)

这是编码问题。尝试在回复中添加此行

 Response.Charset = "utf-8"; 

答案 3 :(得分:0)

现在这有点老了,但是最近我在使用Rotativa / DinkToPDF时遇到了同样的问题。 原来代码很好,但是由于我是通过ajax发布表单而看到的。

我禁用了Ajax表单发布功能,并且有效!

希望这对您有帮助

相关问题