articles

Home / DeveloperSection / Articles / Download files in ASP.NET MVC

Download files in ASP.NET MVC

Chris Anderson 16202 10-Oct-2011

In this article I am explaining how to download files in ASP.NET MVC from the physical drive of the server.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application project as seen below:

Download files in ASP.NET MVC

Choose ASPX as the view engine and click OK.

Download files in ASP.NET MVC

Add a controller and give the name as HomeController.

Download files in ASP.NET MVC

Add folder (ImageFile) in Solution Explorer, also add two file in that folder i.e. Koala.jpg and Penguins.jpg.

Download files in ASP.NET MVC

After adding files create a View (Index) as shown below:

<html>
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
        <table>
            <tr>
                <td>
                    <img src="../../ImageFile/Koala.jpg" width="300" height="300" />
                </td>
                <td>
                    <img src="../../ImageFile/Penguins.jpg" width="300" height="300" />
                </td>
            </tr>
            <tr>
                <td align="center">
                    <a href="/Home/Download/1">Download</a><br />
                </td>
                <td align="center">
                    <a href="/Home/Download/2">Download</a>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

 

Next you have to create an Action method in a controller that returns the file according to id passed to the method. Here if the id passed is as 1 then Koala.jpg file will return and if 2 are passed it will return Penguins.jpg

using System;
using System.Web.Mvc;

namespace DownloadDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public FilePathResult Download(int id)
        {
            string fileName = "";
            if (id == 1)
                fileName = "Koala.jpg";
            if (id == 2)
                fileName = "Penguins.jpg";
            string path = AppDomain.CurrentDomain.BaseDirectory + "ImageFile/";
            return File(path + fileName, "image/jpg", fileName);
        }
    }
}

 

After creating a Controller method the image is displayed on the page as follows:

Download files in ASP.NET MVC

When you click on the Download link the file ready for the download:

Download files in ASP.NET MVC

Thanks for reading this article.


Updated 04-Mar-2020
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By