In this article I will explain with an example, how to download PDF file in ASP.Net Core MVC.
Location of the File
The File to be downloaded is stored in the Files Folder (Directory) inside the wwwroot Folder (Directory).
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called, when Download button is clicked.
Inside this Action method, the path of the File to be downloaded is fetched from the wwwroot Folder (Directory) using IWebHostEnvironment interface.
Then, the File is read as Binary Data into a BYTE Array using the ReadAllBytes method of the File class.
Finally, the BYTE Array is sent for download with content type as octet-stream using the File function.
Note: octet-stream is used to send any type of file in the form of BYTE array over the internet.
public class HomeController : Controller
{
private IWebHostEnvironment Environment { get; set; }
public HomeController(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Download()
{
//Build the File Path.
string path = Path.Combine(this.Environment.WebRootPath, "Files\\Sample.pdf");
//Read the File data into Byte Array.
byte[] bytes = System.IO.File.ReadAllBytes(path);
//Send the File to Download.
return File(bytes, "application/octet-stream", "Sample.pdf");
}
}
View
HTML Markup
The View consists of an HTML Form which has been created using the ASP.Net TagHelpers with the following attributes.
asp-action – Name of the Action. In this case the name is Download.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of an HTML INPUT Submit button.
Submitting the Form
When the Submit Button is clicked then, the form will be submitted to the Controller’s Action method.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-action="Download" asp-controller="Home">
<input type="submit" value="Download" />
</form>
</body>
</html>
Screenshot
Demo
Downloads