C# MVC 网站 PDF 文件以字节数组形式存储,在浏览器中显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16943776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# MVC website PDF file in stored in byte array, display in browser
提问by A Bogus
I am receiving a byte[]which contains a PDF.
我收到一个byte[]包含 PDF 的文件。
I need to take the byte[]and display the PDF in the browser.
I have found similar questions like this - How to return PDF to browser in MVC?.
But, it opens the PDF in a PDF viewer, also I am getting an error saying the file couldn't be opened because it's - "not a supported file type or because the file has been damaged".
我需要在浏览器中获取byte[]并显示 PDF 。我发现了类似的问题 -如何在 MVC 中将 PDF 返回到浏览器?. 但是,它会在 PDF 查看器中打开 PDF,我也收到一条错误消息,说无法打开该文件,因为它是“不支持的文件类型或因为文件已损坏”。
How can I open the PDF in the browser? My code so far looks like the following -
如何在浏览器中打开 PDF?到目前为止,我的代码如下所示 -
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB();
Stream stream = new MemoryStream(byteArray);
stream.Flush();
stream.Position = 0;
return File(stream, "application/pdf", "Labels.pdf");
}
回答by Roberto C.
You can show the byte array PDF directly in your browser simply by using MemoryStreaminstead of Streamand FileStreamResultinstead of File:
您可以直接在浏览器中显示字节数组 PDF,只需使用MemoryStream代替Stream和FileStreamResult代替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");
}
}
回答by Weihui Guo
If you already have the byte[], you should use FileContentResult, which "sends the contents of a binary file to the response". Only use FileStreamResultwhen you have a stream open.
如果您已经有了 byte[],则应该使用FileContentResult,它“将二进制文件的内容发送到响应”。仅FileStreamResult在您打开流时使用。
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB();
return new FileContentResult(byteArray, "application/pdf");
}

