MVC download file

Return value of Controller’s Actions in ASP.NET MVC should be of Action Result type but this doesn’t mean you always should return a View. You may return a file to be downloaded and the file type could be anything e.g. png, mp3, exe and etc. Every extension has a Mime type and depending on the type, an application on the client can open and execute the file. Suppose you want to play an MP3 for the client. In addition to sending the mp3 file for the client to download you should tell the client the content type of the file so the client can open it with an appropriate application.

In ASP.NET MVC the file can be returned to the user using a line like this in an action:

return (ActionResult) this.File(ByteArray, "MIME type","FileName to Return to user");

For example for an mp3 you should put "audio/mpeg" in "MIME type". Converting a file to a byte[] is also as easy as reading it in a MemoryStream and calling ToArray() method on it. 

Read 1253 times Last modified on Sunday, 05 April 2015 07:49
Rate this item
(0 votes)
About Author
Related items
Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Advanced Programming Concepts
News Letter

Subscribe our Email News Letter to get Instant Update at anytime