Vague
Vague

Reputation: 2280

Download File using MVC Core

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?

Upvotes: 21

Views: 31955

Answers (2)

Vague
Vague

Reputation: 2280

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

Upvotes: 44

Ageonix
Ageonix

Reputation: 1808

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>

Upvotes: 1

Related Questions