Wednesday, September 9, 2015

How to download a file in MVC

Provide a easy way to download file in MVC.


File downloading is a kind of  common functionality which we want in our web application. I already have a post which provides the code snippet to be used for this functionality in webforms.

But now the era has changed. Developers are switching to MVC now and so do there comes a need for file downloading snippet. Mostly File downloading is provided in two ways. File are saved in database (i.e. in form of bytes) or File is physically present on application server inside the application hierarchy. The following snippet works for both the scenarios as it uses the BYTES format to provide file as download.


When I started work in MVC for the first time and when the file download task comes in, I had to google for the solution. So purpose of posting this tip is to help the naive's like me to get the solution in easiest way.

Using the code

Following is a simple code snippet which can be used as Action in MVC Controller. It simply picks the file from one folder in application hierarchy, converts it into bytes and return the result as file to View.
  public ActionResult DownloadFile()
            string path = AppDomain.CurrentDomain.BaseDirectory + "FolderName/";
            byte[] fileBytes = System.IO.File.ReadAllBytes(path + "filename.extension");
            string fileName = "filename.extension";
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
 Simply replace the  FolderName  with the folder in which file is present in project hierarchy, and replacefilename.extension with your filename along with extension to make it work properly.. Simply call this in view using the line below.

 @Html.ActionLink("Click here to download", "DownloadFile", new { })

Points of Interest
Many code snippets are available on Google, but I found this one pretty interesting and straight forward for any programmer who is a kind of newbie like myself.
Do give me your feedback,  either suggestions, corrections or praises. Smile | :)  

No comments:

Post a Comment