This article explores how to download files using ASP.NET Core MVC. To begin, we have to create a table for storing file information, such as file names, and a source path. Here’s a step-by-step guide on How to download files in ASP.NET Core MVC.
Create an Asp.NET Core MVC Project
Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project
- Open the visual studio (IDE).
- Click on the “Create new project” option.
- Choose “ASP.NET Core Web Application” from the list of available templates.
- Click the Next button.
- Then configure a new project, and specify the name and location of your project.
- Click the “Next” button.
- Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
- Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
- Click the “Create” button
Open the HomeController.cs file. Create a new method named download:
public IActionResult download(string Filename)
{
var stringpath = Path.Combine(this._env.WebRootPath + Filename);
byte[] bytes = System.IO.File.ReadAllBytes(stringpath);
return File(bytes, "application/octet-stream", Filename);
}
ASP.NET Core provides four file-related response classes that implement the ActionResult interface.
- FileContentResult:
- FileStreamResult:
- VirtualFileResult:
- PhysicalFileResult
The FileResult class is an abstract base class for all file-related response classes in ASP.NET Core. The specific class you use to return a file to the browser depends on how to provide the file content and from where.
- FileContentResult and FileStreamResult can be used to return files from virtual paths within your web application.
- PhysicalFileResult can be used to return a file from the absolute file path.
Open the View Index.cshtml file and add the following code.
@model IEnumerable<WebApplication_Download_Files.Models.FileAssets>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">File List to Download</h1>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Filename)
</th>
<th>
Action
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Filename)
</td>
<td>
@Html.ActionLink("Download File","download",new{Filename = item.FileUrls } )
</td>
</tr>
}
</tbody>
</table>
</div>
Output
See Also:
I want to thank you for your assistance and this post. It’s been great.