djblois
djblois

Reputation: 835

Download File from FileSystem no matter the file type in MVC

I need to download a file from my controller method - that can be of any file type. Everything I can find in Stackoverflow is either downloading from the database or the file type is known. From the code I have found so far this is my code:

public FilePathResult ViewAttachment(string filePath, string fileName)
{
     byte[] fileData = System.IO.File.ReadAllBytes(filePath);
     string contentType = MimeMapping.GetMimeMapping(filePath);

     return File(fileData, contentType, filePath);
}

Unfortunately this is giving me an error on the return file line saying:

Cannot explicitly convert type 'System.Web.Mvc.FileConentResult' to 'System.Web.Mvc.FilePathResult'

Upvotes: 1

Views: 1975

Answers (2)

Julius Depulla
Julius Depulla

Reputation: 1633

Assuming,

 string filePath = "~/App_Data/blogs/";
 string fileName = "myblog.pdf";

 [HttpGet]   
 public FileResult ViewAttachment(string filePath, string fileName)
 {
    var fullpath = Path.Combine(Server.MapPath(filePath), filename );
    return File(fullpath, MimeMapping.GetMimeMapping(fullpath ), "DownloadFileNameHere");
 }

Save your file in App_Data/blogs project directory and include the file in the project. Click on show all files in visual studio. Then right click on the file and select include in project from the context. I have masked my blog project files but you can see what needs to be done in screen shot below enter image description here

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26896

Well, exception text is self-explanatory.

File method returns instance of FileContentResult, not FilePathResult (and FileContentResult doesn't inherited from FilePathResult so explicit cast is impossible).

It should be either

public FileContentResult ViewAttachment(string filePath, string fileName)

or even ActionResult as most common type all xxResult types inherited from.

public ActionResult ViewAttachment(string filePath, string fileName)

Upvotes: 3

Related Questions