You may have seen that controller methods that meet page requests return type objects ActionResult
.
Normally you return HTML content through the method View
controller itself. You can change the return type to a file easily, just return an object FileStreamResult
instead of calling the method View
.
Follows the official documentation.
And an example:
public ActionResult BoloDeFuba()
{
FileStream arquivo = new FileStream(@"c:\bolo de fubá.doc");
FileStreamResult download = new FileStreamResult(arquivo, "application/msword"); // O segundo parâmetro é o Mime type
download.FileDownloadName = "bolo de fubá.doc";
return download;
}
Note that the FileStreamResult
receives any object of the type Stream
. You can mount a file in memory or load from the database instead of loading from a folder when needed or more convenient.
friend, in the case in the line using (var Fs = new Filestream(wayDaImage)) it asks me as parameter a Filemode, in my case that is to downlaod the correct is to use which? Filemode.Open.?
– Jhonatan Jorge de Lima
Exactly. I updated the answer.
– Leonel Sanches da Silva
something else, error in Fs.Toarray(), says that filestream does not have a toarray
– Jhonatan Jorge de Lima
Yes, it would work for
MemoryStream
, not toFileStream
. See my issue.– Leonel Sanches da Silva
Guy worked perfectly however the file name this coming with the name of my method in the action has as I name the file that is downloading?
– Jhonatan Jorge de Lima
Yes, look at my edit. The file name is the third argument.
– Leonel Sanches da Silva
I’d rather this answer than the other for leaving none stream open (even for a short time). But still, I don’t know if it’s really necessary to open the file just for that. + 1 =D
– Jéf Bueno
It worked perfectly, thank you very much !
– Jhonatan Jorge de Lima