Reputation: 835
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
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
Upvotes: 1
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