【问题标题】:C# MVC website PDF file in stored in byte array, display in browserC# MVC 网站 PDF 文件存储在字节数组中,在浏览器中显示
【发布时间】:2013-06-01 09:07:45
【问题描述】:

我收到了一个包含 PDF 的 byte[]

我需要使用byte[] 并在浏览器中显示 PDF。 我发现了类似的问题 - How to return PDF to browser in MVC?。 但是,它会在 PDF 查看器中打开 PDF,而且我收到一条错误消息,指出文件无法打开,因为它是 - “不是受支持的文件类型或因为文件已损坏”。

如何在浏览器中打开 PDF?到目前为止,我的代码如下所示 -

    public ActionResult DisplayPDF()
    {
        byte[] byteArray = GetPdfFromDB();
        Stream stream = new MemoryStream(byteArray);
        stream.Flush(); 
        stream.Position = 0; 

        return File(stream, "application/pdf", "Labels.pdf");
    }

【问题讨论】:

标签: c# asp.net-mvc pdf


【解决方案1】:

您可以直接在浏览器中显示字节数组 PDF,只需使用 MemoryStream 而不是 StreamFileStreamResult 而不是 File

public ActionResult DisplayPDF()
{
    byte[] byteArray = GetPdfFromDB();
    using( MemoryStream pdfStream = new MemoryStream())
    {
        pdfStream.Write(byteArray , 0,byteArray .Length);
        pdfStream.Position = 0;
        return new FileStreamResult(pdfStream, "application/pdf");
    }
}

【讨论】:

  • 嘿!把它放在 using 子句中!
  • @Rob MVC 为您处理 fileresults 中的流,因为您不能将其包装在 using 子句中(流将在 MVC 有机会读取它之前被处理)
  • 使用Response.AddHeader("content-disposition", "inline;filename=Test.pdf");设置文件名,但不立即下载文件。例如,当您拥有 MVC 应用程序时,您可以通过子类化 System.Web.Mvc.Controller 来获得 Response
  • inline + filename 似乎不是正确的标题。 Chrome 和 Firefox 尊重设置的用户名,但 Edge 不尊重。所以要小心并意识到这一点。
【解决方案2】:

如果你已经有了字节[],你应该使用FileContentResult,它“将二进制文件的内容发送到响应”。仅在打开流时使用 FileStreamResult

public ActionResult DisplayPDF()
{
    byte[] byteArray = GetPdfFromDB();

    return new FileContentResult(byteArray, "application/pdf");
}

【讨论】:

  • 这对我来说很完美。使用 JavaScript 打开一个小窗口并调用控制器我能够使用上面的代码从数据库中提取一个 pdf 图像。 window.open('GetInvoiceImage?ExternalImage=' + ExternalImage, 'Image_win', 'width=800,height=500,left=0,top=0,scrollbars=yes,resizable=yes,menubar=yes');跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 2021-11-21
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
相关资源
最近更新 更多