Reza.Hoque
Reza.Hoque

Reputation: 2750

File download asp.net mvc

I am following a tutorial to download file from server. But having some trouble. I must be doing some silly mistake..!!

This is the link that I am following: http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

The requirement is; User will click on a link, the site will take them to a details page. On that details page, there will be a download link. When user will click on that download link, the file will be downloaded.

The problem is, when I click the download link, it does not download the original file. Rather it downloads a HTML file. If I click the HTML file, it shows garbage.

This is my code:

Action:

public ActionResult Download(string path,string name)
    {
        return new DownloadResult { VirtualPath = path, FileDownloadName = name };
    }

The DownloadResult class

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 = this.VirtualPath; //context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}

The only difference from the tutorial and my code is I am using the actual server path.

Any idea??

Upvotes: 3

Views: 9505

Answers (2)

Zach dev
Zach dev

Reputation: 1620

Did you read this?

NEW UPDATE: There is no longer need for this custom ActionResult because ASP.NET MVC now includes one in the box.

Use FileContentResult, http://msdn.microsoft.com/en-us/library/system.web.mvc.filecontentresult.aspx for datails

Upvotes: 3

alexn
alexn

Reputation: 59002

If you need to send a file to the client and you know the path, use the FilePathResult:

public ActionResult Download(string path, string name)
{
    return new FilePathResult(path, contentType) {
         FileDownloadName = name
    }
}

Note that you need to know the content type. If you really don't know, you can use application/octet-stream which makes the browser treat it as a binary.

Upvotes: 7

Related Questions