Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MVC website PDF file in stored in byte array, display in browser

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");
    }
like image 979
A Bogus Avatar asked Jun 05 '13 15:06

A Bogus


1 Answers

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");
}
like image 164
Weihui Guo Avatar answered Oct 16 '22 06:10

Weihui Guo