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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With