File Upload with .NET Core and MVC - Part 1
Users frequently want the ability to upload files to a website. If you are using ASP.NET Core/8 with MVC and Bootstrap 5.x, you know that the normal file upload control does not look like the rest of your Bootstrapped controls. In this blog post you are going to learn how to modify the default look and feel with a couple of other looks to make the file upload control match the rest of the bootstrap styled HTML. In addition, you learn the very basics of uploading a file to a server.
Create a Simple Upload Page
Create a new project using Visual Studio 2022 using the ASP.NET Core Web App (Model-View-Controller) template. Name the new project UploadSample. You are going to create four different samples that show a progression from the simple HTML file upload control to a Bootstrap styled upload control using Font Awesome. Once you have the new project created, open the Views\Index.cshtml file and replace all of the code in this file with the following code.
@{ ViewData["Title"] = "File Upload Samples"; } <div class="mt-4 row"> <div class="col text-center"> <h1>File Upload Samples</h1> </div> </div> <div class="mt-4 row justify-content-center"> <div class="list-group col-5"> <a asp-action="Sample1" asp-controller="Home" class="list-group-item"> Upload Control </a> <a asp-action="Sample2" asp-controller="Home" class="list-group-item"> Style Upload Control Using Bootstrap </a> <a asp-action="Sample3" asp-controller="Home" class="list-group-item"> Select a File </a> <a asp-action="Sample4" asp-controller="Home" class="list-group-item"> Using an Icon </a> <a asp-action="Sample5" asp-controller="Home" class="list-group-item"> Upload File to the Server </a> </div> </div>
Listing 1: Create the index page to call the other samples you are going to create.
Open the Controllers\HomeController.cs file and add five action methods as shown below.
public IActionResult Sample1() { return View(); } public IActionResult Sample2() { return View(); } public IActionResult Sample3() { return View(); } public IActionResult Sample4() { return View(); } public IActionResult Sample5() { return View(); }
Listing 2: Create the action methods to call each sample.
Right mouse-click on the Views\Home folder and add a new view named Sample1.cshtml. Replace the code in this file with the code shown in Listing 3. It is important to set the enctype attribute on the