Upload And Display Image In ASP.NET Core 3.1

In this article, I will explain how to upload and display images. This article will help you to understand image tag helper and IFormFile in asp.net core. Image Tag Helper enhances the img tag to provide cache busting behavior for static image files. A unique cache-busting string is appended as a query parameter to the image source. The file on the host web server changes, a unique request URL is generated that includes the updated request parameter. IFormFile which is a C# representation of the file is used to process or save the file.
 
Here is the complete code.
 
This is how we display images in asp.net core.
  1. <img src="~/images/@employee.ProfilePicture"  class="rounded-circle"height="40" width="40" asp-append-version="true" />  
Step 1
 
Start up Visual Studio 2019. Now click on create new project and Choose ASP.NET Core Web Application and click on “Next”.
 
Upload And Display Image In ASP.NET Core 3.1
 
After clicking next, another wizard will open. Under the project name, give a meaningful name to your project and click on create
 
Upload And Display Image In ASP.NET Core 3.1
 
That will open up another new wizard. Select ASP.Net Core 3.0 from the dropdown. If not, select default. Choose Web Application (Model-View-Controller) template and click on create which will create ASP.Net Core Application.
 
Upload And Display Image In ASP.NET Core 3.1
 
Step 2
 
Now right click on Models folder and “Add” class and name it Employee.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace MvcCoreUploadAndDisplayImage_Demo.Models  
  8. {  
  9.     public class Employee  
  10.     {  
  11.         [Key]  
  12.         public int Id { getset; }  
  13.   
  14.         [Required(ErrorMessage = "Please enter first name")]  
  15.         [Display(Name = "First Name")]  
  16.         [StringLength(100)]  
  17.         public string FirstName { getset; }  
  18.   
  19.         [Required(ErrorMessage = "Please enter last name")]  
  20.         [Display(Name = "Last Name")]  
  21.         [StringLength(100)]  
  22.         public string LastName { getset; }  
  23.   
  24.         [Display(Name = "Full Name")]  
  25.         public string FullName { getset; }  
  26.   
  27.         [Required(ErrorMessage = "Please enter age")]  
  28.         public int Age { getset; }  
  29.   
  30.         [Required(ErrorMessage = "Please choose gender")]  
  31.         public string Gender { getset; }  
  32.   
  33.         [Required(ErrorMessage = "Please enter position")]  
  34.         public string Position { getset; }  
  35.   
  36.         [Required(ErrorMessage = "Please enter office")]  
  37.         public string Office { getset; }  
  38.   
  39.         [Required(ErrorMessage = "Please enter salary")]  
  40.         public int Salary { getset; }  
  41.   
  42.         [Required(ErrorMessage = "Please choose profile image")]  
  43.         public string ProfilePicture { getset; }  
  44.   
  45.         public Employee()  
  46.         {  
  47.             FullName = FirstName + " " + LastName;  
  48.         }  
  49.     }  
  50. }   
Step 3
 
Right click on project “Add” folder ViewModels and “Add” class EmployeeViewModel.
  1. using Microsoft.AspNetCore.Http;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace MvcCoreUploadAndDisplayImage_Demo.ViewModels  
  5. {  
  6.     public class EmployeeViewModel  
  7.     {  
  8.         [Required(ErrorMessage = "Please enter first name")]  
  9.         [Display(Name = "First Name")]  
  10.         public string FirstName { getset; }  
  11.   
  12.         [Required(ErrorMessage = "Please enter last name")]  
  13.         [Display(Name = "First Name")]  
  14.         public string LastName { getset; }  
  15.   
  16.         [Required(ErrorMessage = "Please enter age")]  
  17.         public int Age { getset; }  
  18.   
  19.         [Required(ErrorMessage = "Please choose gender")]  
  20.         public string Gender { getset; }  
  21.   
  22.         [Required(ErrorMessage = "Please enter position")]  
  23.         public string Position { getset; }  
  24.   
  25.         [Required(ErrorMessage = "Please enter office")]  
  26.         public string Office { getset; }  
  27.   
  28.         [Required(ErrorMessage = "Please enter salary")]  
  29.         public int Salary { getset; }  
  30.   
  31.         [Required(ErrorMessage = "Please choose profile image")]  
  32.         [Display(Name = "Profile Picture")]  
  33.         public IFormFile ProfileImage { getset; }  
  34.     }  
  35. }   
Step 4
 
Now click on ApplicationDbContext which is under Data folder of your project. “Add” your Employee as DbSet.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
  5. using Microsoft.EntityFrameworkCore;  
  6. using MvcCoreUploadAndDisplayImage_Demo.Models;  
  7.   
  8. namespace MvcCoreUploadAndDisplayImage_Demo.Data  
  9. {  
  10.     public class ApplicationDbContext : IdentityDbContext  
  11.     {  
  12.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)  
  13.             : base(options)  
  14.         {  
  15.         }  
  16.   
  17.         public DbSet<Employee> Employees { getset; }  
  18.     }  
  19. }   
Step 5
 
Now create images folder under wwwroot folder of the project.
 
Step 6
 
Now go to tools, select nuget package manager, then click on package manager console. It will bring the console window below in Visual Studio 2019. Now write the following commands to enable migration.
  • add-migration InitialModel (add migration can be anything you wish to)
  • update-database
Step 7
 
Now open HomeController which is added when we created new project. Write the following code for Index and New IActionResult methods.
 
Controller Complete Code
  1. using Microsoft.AspNetCore.Hosting;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.EntityFrameworkCore;  
  4. using MvcCoreUploadAndDisplayImage_Demo.Data;  
  5. using MvcCoreUploadAndDisplayImage_Demo.Models;  
  6. using MvcCoreUploadAndDisplayImage_Demo.ViewModels;  
  7. using System;  
  8. using System.IO;  
  9. using System.Threading.Tasks;  
  10.   
  11. namespace MvcCoreUploadAndDisplayImage_Demo.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.   
  16.         private readonly ApplicationDbContext dbContext;  
  17.         private readonly IWebHostEnvironment webHostEnvironment;  
  18.         public HomeController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)  
  19.         {  
  20.             dbContext = context;  
  21.             webHostEnvironment = hostEnvironment;  
  22.         }  
  23.   
  24.         public async Task<IActionResult> Index()  
  25.         {  
  26.             var employee = await dbContext.Employees.ToListAsync();  
  27.             return View(employee);  
  28.         }  
  29.   
  30.         public IActionResult New()  
  31.         {  
  32.             return View();  
  33.         }  
  34.   
  35.         [HttpPost]  
  36.         [ValidateAntiForgeryToken]  
  37.         public async Task<IActionResult> New(EmployeeViewModel model)  
  38.         {  
  39.             if (ModelState.IsValid)  
  40.             {  
  41.                 string uniqueFileName = UploadedFile(model);  
  42.   
  43.                 Employee employee = new Employee  
  44.                 {  
  45.                     FirstName = model.FirstName,  
  46.                     LastName = model.LastName,  
  47.                     FullName = model.FirstName +" "+ model.LastName,  
  48.                     Gender = model.Gender,  
  49.                     Age = model.Age,  
  50.                     Office = model.Office,  
  51.                     Position = model.Position,  
  52.                     Salary = model.Salary,  
  53.                     ProfilePicture = uniqueFileName,  
  54.                 };  
  55.                 dbContext.Add(employee);  
  56.                 await dbContext.SaveChangesAsync();  
  57.                 return RedirectToAction(nameof(Index));  
  58.             }  
  59.             return View();  
  60.         }  
  61.   
  62.         private string UploadedFile(EmployeeViewModel model)  
  63.         {  
  64.             string uniqueFileName = null;  
  65.   
  66.             if (model.ProfileImage != null)  
  67.             {  
  68.                 string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");  
  69.                 uniqueFileName = Guid.NewGuid().ToString() + "_" + model.ProfileImage.FileName;  
  70.                 string filePath = Path.Combine(uploadsFolder, uniqueFileName);  
  71.                 using (var fileStream = new FileStream(filePath, FileMode.Create))  
  72.                 {  
  73.                     model.ProfileImage.CopyTo(fileStream);  
  74.                 }  
  75.             }  
  76.             return uniqueFileName;  
  77.         }  
  78.     }  
  79. }  
Step 8
 
Right click on New IActionResult method. “Add” view with default name “New”. Write the following code.
  1. @model MvcCoreUploadAndDisplayImage_Demo.ViewModels.EmployeeViewModel  
  2.   
  3. @{  
  4.     ViewData["Title"] = "New";  
  5. }  
  6.   
  7. <div class="col-md-10 mx-auto py-4">  
  8.     <div class="card">  
  9.         <div class="card-header bg-primary text-uppercase text-white">  
  10.             <h4>Add New </h4>  
  11.         </div>  
  12.         <div class="card-body">  
  13.             <form enctype="multipart/form-data" asp-action="New">  
  14.                 <div class="row">  
  15.                     <div class="col-md-6">  
  16.                         <div class="form-group">  
  17.                             <label asp-for="FirstName" class="control-label"></label>  
  18.                             <input asp-for="FirstName" class="form-control" />  
  19.                             <span asp-validation-for="FirstName" class="text-danger"></span>  
  20.                         </div>  
  21.                     </div>  
  22.                     <div class="col-md-6">  
  23.                         <div class="form-group">  
  24.                             <label asp-for="LastName" class="control-label"></label>  
  25.                             <input asp-for="LastName" class="form-control" />  
  26.                             <span asp-validation-for="LastName" class="text-danger"></span>  
  27.                         </div>  
  28.                     </div>  
  29.                 </div>  
  30.                 <div class="row">  
  31.                     <div class="col-md-6">  
  32.                         <div class="form-group">  
  33.                             <label asp-for="Gender" class="control-label"></label>  
  34.                             <select asp-for="Gender" class="form-control">  
  35.                                 <option value="">Choose Gender</option>  
  36.                                 <option value="Male">Male</option>  
  37.                                 <option value="Female">Female</option>  
  38.                             </select>  
  39.                             <span asp-validation-for="Gender" class="text-danger"></span>  
  40.                         </div>  
  41.                     </div>  
  42.                     <div class="col-md-6">  
  43.                         <div class="form-group">  
  44.                             <label asp-for="Age" class="control-label"></label>  
  45.                             <input asp-for="Age" class="form-control" />  
  46.                             <span asp-validation-for="Age" class="text-danger"></span>  
  47.                         </div>  
  48.                     </div>  
  49.                 </div>  
  50.                 <div class="row">  
  51.                     <div class="col-md-6">  
  52.                         <div class="form-group">  
  53.                             <label asp-for="Position" class="control-label"></label>  
  54.                             <input asp-for="Position" class="form-control" />  
  55.                             <span asp-validation-for="Position" class="text-danger"></span>  
  56.                         </div>  
  57.                     </div>  
  58.                     <div class="col-md-6">  
  59.                         <div class="form-group">  
  60.                             <label asp-for="Office" class="control-label"></label>  
  61.                             <input asp-for="Office" class="form-control" />  
  62.                             <span asp-validation-for="Office" class="text-danger"></span>  
  63.                         </div>  
  64.                     </div>  
  65.                 </div>  
  66.                 <div class="row">  
  67.                     <div class="col-md-6">  
  68.                         <div class="form-group">  
  69.                             <label asp-for="Salary" class="control-label"></label>  
  70.                             <input asp-for="Salary" class="form-control" />  
  71.                             <span asp-validation-for="Salary" class="text-danger"></span>  
  72.                         </div>  
  73.                     </div>  
  74.                     <div class="col-md-6">  
  75.                         <div class="form-group">  
  76.                             <label asp-for="ProfileImage" class="control-label"></label>  
  77.                             <div class="custom-file">  
  78.                                 <input asp-for="ProfileImage" class="custom-file-input" id="customFile">  
  79.                                 <label class="custom-file-label" for="customFile">Choose file</label>  
  80.                             </div>  
  81.                             <span asp-validation-for="ProfileImage" class="text-danger"></span>  
  82.                         </div>  
  83.                     </div>  
  84.                 </div>  
  85.                 <div class="form-group">  
  86.                     <input type="submit" value="submit" class="btn btn-sm btn-primary rounded-0 text-uppercase" />  
  87.                     <a asp-action="Index" class="btn btn-sm btn-primary rounded-0 text-uppercase"><i class="fas fa-fast-backward"></i> Back to List</a>  
  88.                 </div>  
  89.             </form>  
  90.         </div>  
  91.     </div>  
  92. </div>  
  93.   
  94. @section scripts{  
  95.     <script type="text/javascript">  
  96.         // Add the following code if you want the name of the file appear on select  
  97.         $(".custom-file-input").on("change", function () {  
  98.             var fileName = $(this).val().split("\\").pop();  
  99.             $(this).siblings(".custom-file-label").addClass("selected").html(fileName);  
  100.         });  
  101.     </script>  
  102. }  
Step 9 
 
Right click on Index IActionResult method “Add” view with default name “Index.” If you don't have it then write the following code.
  1. @model IEnumerable<MvcCoreUploadAndDisplayImage_Demo.Models.Employee>  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Home Page";  
  5. }  
  6.   
  7. <h4 class="text-center text-uppercase">List of employee</h4>  
  8.   
  9. <p>  
  10.     <a asp-action="New" class="btn btn-sm btn-primary rounded-0 text-uppercase"><i class="fas fa-plus-circle"></i> Add New</a>  
  11. </p>  
  12. <table class="table table-bordered">  
  13.     <thead>  
  14.         <tr>  
  15.             <th>@Html.DisplayNameFor(model => model.FullName)</th>  
  16.             <th>@Html.DisplayNameFor(model => model.Gender)</th>  
  17.             <th>@Html.DisplayNameFor(model => model.Age)</th>  
  18.             <th>@Html.DisplayNameFor(model => model.Position)</th>  
  19.             <th>@Html.DisplayNameFor(model => model.Office)</th>  
  20.             <th>@Html.DisplayNameFor(model => model.Salary)</th>  
  21.         </tr>  
  22.     </thead>  
  23.     <tbody>  
  24.         @foreach (var employee in Model)  
  25.         {  
  26.             <tr>  
  27.                 <td>  
  28.                     <img src="~/images/@employee.ProfilePicture"   
  29.                          class="rounded-circle"   
  30.                          height="40" width="40"   
  31.                          asp-append-version="true" />  
  32.                     @employee.FullName  
  33.                 </td>  
  34.                 <td>@employee.Gender</td>  
  35.                 <td>@employee.Age</td>  
  36.                 <td>@employee.Office</td>  
  37.                 <td>@employee.Position</td>  
  38.                 <td>@employee.Salary</td>  
  39.             </tr>  
  40.         }  
  41.     </tbody>  
  42. </table>   
Step 10  
 
Build and Run your application by pressing ctrl+F5
 
Upload And Display Image In ASP.NET Core 3.1
Upload And Display Image In ASP.NET Core 3.1