Tuesday, June 23, 2009

File Download with ASP.NET MVC

One of the things that might be less obvious when doing applications with ASP.NET MVC, is the ability to download files without exposing your files directly and possibly applying other mechanisms such as authentication or registering emails before allowing someone download your files. This is pretty much easy. The “Controller” class has a File method which returns a “FilePathResult”.

public class DownloadsController : Controller
{
private readonly IProductService _productService;

public DownloadsController(IProductService productService)
{
_productService = productService;
}

[SessionPerRequest]
public ActionResult Index()
{
var products = _productService.GetDownloadableProducts();
var model = new DownloadViewModel(products);

return View(model);
}

[SessionPerRequest]
public ActionResult File(int id)
{
var download = _productService.FindDownload(id);

if (download != null)
{
var path = Server.MapPath(download.URL);
var file = new FileInfo(path);
if (file.Exists)
{
return File(download.URL, "application/binary", download.FileName);
}
}

return RedirectToAction("Index");
}
}

<table>

<% foreach (var p in Model.Products) { %>
<tr>
<td>
<
strong><%= p.Title %></strong><br />

<%foreach(var d in p.Downloads) { %>

<a href="/Downloads/File/<%= d.Id %>">
Version: <%= d.Version %>- <%= d.DownloadSize %> KB
</a>
<
br />
<%} %>

</td>
</
tr>
<% } %>

</table>


Submit this story to DotNetKicks Shout it

No comments: