Show or Download File Correctly in ASP.NET MVC3 When File Type Isn't Text or Picture

1k Views Asked by At

This is My Action:

public FileResult ShowFile(long Id) {

    DAL.Files.File file = new DAL.Files.FileAccess().GetById(Id);
    return File(file.Content, file.FileType);
}

GetById method return a file from SQL DB, when the file type is text or picture every thing is OK and correctly shown file, but when the file type is different like PDF that show some Unicode, so how can I shown PDF file correctly, or let the user download it?

2

There are 2 best solutions below

0
On

The second argument to the File() method needs to be a mime type. So say your file is a PDF, it should work if you do this:

public FileResult ShowFile(long Id) {

    DAL.Files.File file = new DAL.Files.FileAccess().GetById(Id);
    // assuming file is a PDF
    return File(file.Content, "application/pdf");
}

To force a download instead, use the File() overload that takes a 3rd argument:

public FileResult ShowFile(long Id) {

    DAL.Files.File file = new DAL.Files.FileAccess().GetById(Id);
    // assuming file is a PDF
    return File(file.Content, "application/pdf", "some-pdf-file.pdf");
}
0
On

As mentioned above you need to add the appklication/pdf, however I also needed the headers to be correct.

    public FileResult ShowFile(long Id)
    {

        DAL.Files.File file = new DAL.Files.FileAccess().GetById(Id);
        // assuming file is a PDF
        Response.AppendHeader("Content-Disposition", "inline; filename=CustomInvoice.pdf");
        return File(file.Content, "application/pdf", "some-pdf-file.pdf");
    }