views:

261

answers:

2

I am new to ASP.NET MVC, and am trying to link to downloadable files (.zip, .mp3, .doc, etc).

I have the following view: ProductName

which maps to: http://domain/ProductName

I have a .zip file that must map to URL http://domain/ProductName/Product.zip

Questions

Where do I place this .zip file in the MVC folder structure?

How do I add link to this .zip file in MVC? Is there a Url.* method that do this?

+5  A: 

The following class adds a file DownloadResult to your program:

public class DownloadResult : ActionResult
{

    public DownloadResult()
    {
    }

    public DownloadResult(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath { get; set; }

    public string FileDownloadName { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (!String.IsNullOrEmpty(FileDownloadName))
        {
            context.HttpContext.Response.AddHeader("content-disposition",
              "attachment; filename=" + this.FileDownloadName);
        }

        string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}

To call it, do something like this in your controller method:

public ActionResult Download(string name)
{
    return new DownloadResult 
       { VirtualPath = "~/files/" + name, FileDownloadName = name };
}

Note the virtual path, which is a files directory in the root of the site; this can be changed to whatever folder you want. This is where you put your files for download.

http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

Robert Harvey
+1. Good solution.
George Stocker
Yes this solution works. But as Phil Haack indicated, ASP.Net MVC already has this implemented as part of FilePathResult.
goths
+3  A: 

You can use FilePathResult or Controller.File method.

protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName) {
  return new FilePathResult(fileName, contentType) { FileDownloadName = fileDownloadName };
}

Sample code action method.

public ActionResult Download(){
  return File(fileName,contentType,downloadFileName);
}

Hope this code.

takepara