Software Prerequisites
To follow this tutorial, ensure you have the following tools installed on your development machine.
Development IDE
Runtime Framework
File Location in Project
The files to be downloaded are stored in a folder named Files located within the wwwroot folder.
The screenshot below shows the Solution Explorer.
Controller Logic
IWebHostEnvironment Dependency injection
The Constructor is injected access the IWebHostEnvironment service.
Note: The IWebHostEnvironment service is the standard way to retrieve the physical path of the wwwroot folder.
private readonly IWebHostEnvironment _env;
//Dependency Injection
public HomeController(IWebHostEnvironment env)
{
_env = env;
}
The Controller manages the file download process through two primary action methods:
Handling GET Requests
This method is used to load the initial page. It simply returns the Index view to the browser.
public IActionResult Index()
{
return View();
}
Handling File Download operation
This method processes the actual file download and when the ActionLink is clicked, the name of the File to be downloaded is sent to this method.
First, the File’s path is generated by combining the Directory.GetCurrentDirectory(), wwwroot and the Files folder.
Then using the ReadAllBytes method, the file is read as Binary Data into a Byte Array object
Finally, the Byte Array object is sent for download using the File function.
public async Task<IActionResult> DownloadFile(string fileName)
{
//Build the File Path.
string path = Path.Combine(_env.WebRootPath, "wwwroot", "Files", fileName);
if (System.IO.File.Exists(path))
{
//Read the File data into Byte Array.
byte[]bytes = System.IO.File.ReadAllBytes(path);
//Send the File to Browser.
return File(bytes,"application/octet-stream",fileName);
}
else
{
return NotFound();
}
}
View (HTML)
In this section the file downloading is done using a standard HTML Form. There is an ActionLink for downloading the File.
When the ActionLink is clicked, it executes DownloadFile Action method and the File is downloaded.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@Html.ActionLink("Download", "DownloadFile", new {fileName = "Mudassar_Khan.pdf" })
</body>
</html>
Logic Breakdown
ActionLink parameters
The first parameter is the Text which be displayed, the second parameter is the name of Action method and the third parameter is the parameter value to be passed to the Action method.
Screenshot
Downloads