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:
Choose ASPX as the view engine and click OK.
Add a controller and give the name as HomeController.
Add folder (ImageFile) in Solution Explorer, also add two file in that folder i.e. Koala.jpg and Penguins.jpg.
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:
When you click on the Download link the file ready for the download:
Leave Comment