I\'m editing some code and there is one method which return FileContentResult
type. I get a stream from service, so for me it would be more convenient to change
FileResult
is an abstract base class for all the others.
FileContentResult
- use it when you have a byte array you would
like to return as a fileFileStreamResult
- you have a stream open, you want to return it's
content as a fileBoth FileStreamResult
and FileContentResult
inherit from FileResult
which inherits from ActionResult
. So you can return either one type from a method which has ActionResult
as the return type
If you already have a stream, you can use FileStreamResult
constructor to return a FileResult
public ActionResult Download()
{
var f = Server.MapPath("~/Content/mypdf.pdf");
var fileStream = new FileStream(f,FileMode.Open,FileAccess.Read);
return new FileStreamResult(fileStream, MimeMapping.GetMimeMapping(f));
}
If you already have a byte arrray, you can use FileContentResult
constructor to return a FileResult
public ActionResult Download()
{
var f = Server.MapPath("~/Content/mypdf.pdf");
var bytes = System.IO.File.ReadAllBytes(f);
return new FileContentResult(bytes, MimeMapping.GetMimeMapping(f));
}
The Controller.File
method has overloads which takes either a byte array or a stream
public ActionResult Download()
{
var f = Server.MapPath("~/Content/mypdf.pdf");
var bytes = System.IO.File.ReadAllBytes(f);
return File(bytes, MimeMapping.GetMimeMapping(f));
}
public ActionResult Download2()
{
var f = Server.MapPath("~/Content/mypdf.pdf");
var fileStream = new FileStream(f, FileMode.Open, FileAccess.Read);
return File(fileStream, MimeMapping.GetMimeMapping(f));
}
If the browser has the support to display the content type of the response, the response will be displayed in the browser. For example, for the above code, it will display the pdf content in the browser.
There is another overload of the File
method which takes the download file name which the browsers' save/download dialog will use so that user can save it his local computer and/or open.
public ActionResult Download4()
{
var f = Server.MapPath("~/Content/mypdf.pdf");
var fileStream = new FileStream(f, FileMode.Open, FileAccess.Read);
return File(fileStream, MimeMapping.GetMimeMapping(f),"MyfileNiceFileName.pdf");
}
With this, user will get a download prompt from the browser.