Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Downloading individual files

I have an MVC3 C#.Net web app. We have an "Attachment" feature. The user uploads a document they want to "Attach" to a Proposal. This document is stored on our server waiting to be downloaded. This part is working.

The user then clicks on the name of the "Attachment" that is displayed as a Hyperlink in a table. I'm sure there is a common way to do this. I just don't know how. How do I download a file using a hyperlink?

like image 270
MikeTWebb Avatar asked Jan 17 '23 19:01

MikeTWebb


1 Answers

To download a file using a hyperlink, you first need to have your action link pass the file name as a route value to the action:

@Html.ActionLink("Download", "Download", 
                 new { fileName = Model.AttachmentFileName })

Your action will take in fileName, open it for reading under /some/path, and return it using ASP.NET MVC's built in FileStreamResult:

public ActionResult Download(string fileName)
{
    try
    {
        var fs = System.IO.File.OpenRead(Server.MapPath("/some/path/" + fileName));
        return File(fs, "application/zip", fileName);
    }
    catch
    {
        throw new HttpException(404, "Couldn't find " + fileName);
    }
}

The application/zip parameter is the MIME type of what you're returning. In this case it's a .zip file.

Here is a list of possible MIME types.

like image 65
Lester Avatar answered Jan 31 '23 18:01

Lester