How to download a file to the client from the server?

I have an MVC project where I want the user to be able to download an excel file with the click of a button. I have a file path and I cannot find the answer via Google.

I would like to be able to do this with the simple button that I have on my cshtml page:

<button>Button 1</button> 

How can i do this? Any help is much appreciated!

+5
source share
2 answers

If the file is not inside your application folders and is not accessible directly from the client, you can have a controller action that will transfer the contents of the file to the client. This can be achieved by returning a FileResult from your controller action using the File method:

 public ActionResult Download() { string file = @"c:\someFolder\foo.xlsx"; string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; return File(file, controntType, Path.GetFileName(file)); } 

and then replace your button with an anchor pointing to this controller action:

 @Html.ActionLink("Button 1", "Download", "SomeController") 

As an alternative to using an anchor, you can also use the html form:

 @using (Html.BeginForm("Download", "SomeController", FormMethod.Post)) { <button type="submit">Button 1</button> } 

If the file is inside some not accessible from the client folder of your application, such as App_Data , you can use MapPath to build the full physical path to this file using the relative path:

 string file = HostingEnvironment.MapPath("~/App_Data/foo.xlsx"); 
+11
source

HTML:

 <div>@Html.ActionLink("UI Text", "function_name", "Contoller_name", new { parameterName = parameter_value },null) </div> 

Controller:

 public FileResult download(string filename) { string path = ""; var content_type = ""; path = Path.Combine("D:\file1", filename); if (filename.Contains(".pdf")) { content_type = "application/pdf"; } return File(path, content_type, filename); } 
+2
source

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


All Articles