C# MVC website PDF file in stored in byte array, d

2020-08-22 03:27发布

问题:

I am receiving a byte[] which contains a 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".

How can I open the PDF in the browser? My code so far looks like the following -

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

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

回答1:

You can show the byte array PDF directly in your browser simply by using MemoryStream instead of Stream and FileStreamResult instead of 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");
    }
}


回答2:

If you already have the byte[], you should use FileContentResult, which "sends the contents of a binary file to the response". Only use FileStreamResult when you have a stream open.

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

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