Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download File using MVC Core

Tags:

I cannot find a reference to downloading a file using MVC Core.

We have a single exe file for members to download from our website. In the past we have put

<a href=(file path)> Download < /a> for our users to click. I would like to do something equivalent in MVC Core along the lines of

<a href=@ViewData["DownloadLink"]> Download < /a> 

with DownloadLink populated with the file path.

public class DownloadController : Controller {     [HttpGet]     public IActionResult Index()     {         ViewData["DownloadLink"] = ($"~/Downloads/{V9.Version}.exe");         return View();     } } 

`

The link <a href=@ViewData["DownloadLink"]> Download < /a> gets the correct path, but when clicked only renders the path in the address bar. Is there a simple way to set a download link?

like image 235
Vague Avatar asked Feb 06 '16 05:02

Vague


2 Answers

I used this answer posted by @Tieson T to come up with this solution

    public FileResult Download()     {         var fileName = $"{V9.Version}.exe";         var filepath = $"Downloads/{fileName}";         byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);         return File(fileBytes, "application/x-msdownload", fileName);     } 

The view is now

<a asp-action="Download" asp-> Download 

@Ageonix was also correct about not requiring the ~ to get to wwwroot

like image 148
Vague Avatar answered Oct 09 '22 04:10

Vague


I'm not somewhere where I can try it, but would something like this do the trick?

<a href="<%= Url.Content('~/Downloads/{ V9.Version}.exe') %>"> Download </a> 
like image 33
Ageonix Avatar answered Oct 09 '22 02:10

Ageonix