21

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?

Vague
  • 2,198
  • 3
  • 18
  • 46

2 Answers2

44

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

Community
  • 1
  • 1
Vague
  • 2,198
  • 3
  • 18
  • 46
1

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>
Ageonix
  • 1,748
  • 2
  • 19
  • 32
  • Thank you @Ageonix for the suggestion but VS2015 is complaining href is missing a closing angle bracket. I assume that is to do the with double-quotes within double-quotes but I can't get it right. – Vague Feb 06 '16 at 06:16
  • Oops. Try using a single tick on those inner quotes instead. – Ageonix Feb 06 '16 at 06:17
  • 1
    I'm not sure how your site structure is, but if you're getting a 400 are you sure you need the tilde (~) on there? In other words, have you double-checked to see if you're getting to the right place? – Ageonix Feb 06 '16 at 06:32
  • None of the variations on @Ageonix. answer seems to parse the path correctly. My first attempt gets the correct path, but doesn't download. Is this an MVC thing ... the path has to point to a controller action and cannot point to a file to download? – Vague Feb 06 '16 at 21:24