ASP.NET MVC: Download File using FileResult

Updated on     Kisan Patel

This tutorial will show you how to download and render any file using built in controller action called FileResult in ASP.NET MVC.

In ASP.NET MVC, FileResult class represents a base class that is used to send binary file content to the response.

You can use below line of code to render file into your browser:

public class HomeController : Controller
{
    public FileResult GetFiles()
    {
        var path = Server.MapPath(@"~/Images/Desert.jpg");
        var contents = System.IO.File.ReadAllBytes(path);
        return File(contents, "image/jpeg");
    }
}

When you run the project, you can see above code will render the image into browsers as shown in below screenshot:

FileResult-demo-mvc

If you want to download file forcefully you can use below line of code:

public class HomeController : Controller
{
    public FileResult DownloadFiles()
    {
        var path = Server.MapPath(@"~/Images/Desert.jpg");
        var contents = System.IO.File.ReadAllBytes(path);

        var header = new System.Net.Mime.ContentDisposition()
        {
            FileName = "Desert.jpg",
            Inline = false
        };
 
        Response.AddHeader("Content-Disposition", header.ToString());

        return File(contents, "image/jpeg");
    }
}

To download the file, we need to sets the content-disposition header so that a file-download dialog box is displayed in the browser with the specified file name.

Download Complete Source Code


ASP.NET MVC

Leave a Reply