MVC3 Download Single Files

I have a MVC3 C # .Net web application. We have the Attachment feature. The user uploads the document that they want to "Attach" to the proposal. This document is stored on our server, which is awaiting download. This part works.

Then the user clicks on the name "Attachments", which is displayed as a hyperlink in the table. I am sure there is a general way to do this. I just don't know how to do this. How to upload a file using a hyperlink?

+4
source share
1 answer

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

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

Your action will take fileName , open it for reading in /some/path and return it using the ASP.NET MVC built into 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 are returning. In this case, it is a .zip file.

Here is a list of possible MIME types.

+9
source

Source: https://habr.com/ru/post/1390721/


All Articles