65.9K
CodeProject is changing. Read more.
Home

How To Download a File in MVC

Sep 10, 2015

CPOL

1 min read

viewsIcon

89538

Provide an easy way to download file in MVC

Introduction

File downloading is a kind of common functionality which we want in our web application. I already have a post http://www.codeproject.com/Tips/663277/File-Download-on-ImageButton-or-Button-Click 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 there comes a need for file downloading snippet. Mostly file downloading is provided in two ways. Files 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.

Background

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, the purpose of posting this tip is to help the naive programmer like me to get the solution in the 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 replace filename.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 | :)