Introduction :
In this tutorial, I will explain File(Image) Upload in ASP.NET Core MVC with Example. This tutorial 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.
Tools we have used
Asp.Net core 3.1 , visual studio 2019 and Sql server database
Step 1 : Create Asp.Net Mvc web application for File(Image) Upload in ASP.NET Core MVC
Step 2 : Create sql database
Here we will create sql database and create one table named “Employee” then after create store procedure to retrieve data and image path or name from database.
Create Sql table “Employee”
CREATE TABLE [dbo].[Employee]( [UserID] [int] IDENTITY(1,1) NOT NULL, [UserName] [nvarchar](50) NULL, [City] [nvarchar](50) NULL, [State] [nvarchar](50) NULL, [Mobile] [nvarchar](50) NULL, [Profile] [nvarchar](50) NULL, [ProfileImage] [varchar](100) NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [UserID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
Store procedure for Insert Employee data and images
ALTER PROCEDURE [dbo].[Employee_InsertUpdate] @UserName nvarchar(50), @City nvarchar(50) , @State nvarchar(50) , @Mobile nvarchar(50) , @Profile nvarchar(50), @ProfileImage nvarchar(50) AS BEGIN Insert into Employee (UserName,City,State,Mobile,Profile,ProfileImage) VALUES (@UserName,@City,@State,@Mobile,@Profile,@ProfileImage) END
Store procedure for View all Employee Records
CREATE PROCEDURE [dbo].[EMPLOYEE_SELECT] @UserID int =0 AS if(@UserID>0) begin select * from Employee where UserID=@UserID end else begin select * from Employee end
Step 3 : Create model class
After Creating web application we will create a model class named “EmployeeModel” and viewmodel named “EmployeeViewModel” within model folder
public class EmployeeModel { public int UserID { get; set; } public string UserName { get; set; } public string City { get; set; } public string State { get; set; } public string Mobile { get; set; } public string Profile { get; set; } public string ProfileImage { get; set; } } public class EmployeeViewModel { public int UserID { get; set; } public string UserName { get; set; } public string City { get; set; } public string State { get; set; } public string Mobile { get; set; } public string Profile { get; set; } public string ProfileImage { get; set; } public IFormFile Photo { get; set; } }
Step 4 : Now Create one folder and named it repository
For data access layer we have used repository patter, so can you create one folder with named “Repository” and add interface with named “IEmployeeRepository.cs” also create one class with named “EmployeeRepository.cs” this class will implement interface methods
Interface : IEmployeeRepository.cs
public interface IEmployeeRepository { void AddUpdateEmployee(EmployeeModel employee); List GetAllEmployee(); }
Now we will create class named “EmployeeRepository.cs” here in this class we will implement all interface method
EmployeeRepository.cs
public class EmployeeRepository : IEmployeeRepository { private readonly IConfiguration configuration; private string Sqlconnection() { return configuration.GetConnectionString("MySqlCon").ToString(); } public EmployeeRepository(IConfiguration configuration) { this.configuration = configuration; } public void AddUpdateEmployee(EmployeeModel em) { using (var con = new SqlConnection(this.Sqlconnection())) { try { SqlCommand cmd; con.Open(); cmd = new SqlCommand("Employee_InsertUpdate", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserID", em.UserID); cmd.Parameters.AddWithValue("@UserName", em.UserName); cmd.Parameters.AddWithValue("@City", em.City); cmd.Parameters.AddWithValue("@State", em.State); cmd.Parameters.AddWithValue("@Mobile", em.Mobile); cmd.Parameters.AddWithValue("@Profile", em.Profile); cmd.Parameters.AddWithValue("@ProfileImage", em.ProfileImage); cmd.ExecuteNonQuery(); con.Close(); } catch (Exception) { throw; } } } public List GetAllEmployee() { try { using (var con = new SqlConnection(this.Sqlconnection())) { DataTable dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter("EMPLOYEE_SELECT", con); adp.Fill(dt); List lst = new List(); foreach (DataRow dr in dt.Rows) { EmployeeModel em = new EmployeeModel(); em.UserID = Convert.ToInt32(dr["UserID"]); em.UserName = Convert.ToString(dr["UserName"]); em.Mobile = Convert.ToString(dr["Mobile"]); em.Profile = Convert.ToString(dr["Profile"]); em.State = Convert.ToString(dr["State"]); em.City = Convert.ToString(dr["City"]); em.ProfileImage = Convert.ToString(dr["ProfileImage"]); lst.Add(em); } return lst; } } catch (Exception) { throw; } } }
STEP 5: Create Connection String and get it on Repository Class
Now we have to define our database connection string. As we know Asp.Net Core uses appsettings.json to define your app related all configurations. So, we are going to add our connection string inside the appsettings.json file as follows
For getting connection string dynamic way refer our tutorial – Asp.Net Core: Read Connection String dynamically from AppSettings.json file
Step 6: Configure dependency injection in statup.cs
Here we have used repository pattern so we need first to register it on startup.cs file inside ConfigurService methode
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSingleton(Configuration); services.AddTransient<IEmployeeRepository, EmployeeRepository>(); }
Step 7: Create Razor View
Now we will create Razor view for insert and displaying image in gridview, so now we will creating below razor view inside the view folder
- AddEmploye.cshtml
- Index.cshtml
AddEmployee.cshtml
@model DotNetCoreRepository.Models.EmployeeViewModel @{ ViewData["Title"] = ""; } <h5>Add New Employee</h5> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="AddEmployee"enctype="multipart/form-data"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="UserName" class="control-label"></label> <input asp-for="UserName" class="form-control" /> <span asp-validation-for="UserName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="City" class="control-label"></label> <input asp-for="City" class="form-control" /> <span asp-validation-for="City" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="State" class="control-label"></label> <input asp-for="State" class="form-control" /> <span asp-validation-for="State" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Mobile" class="control-label"></label> <input asp-for="Mobile" class="form-control" /> <span asp-validation-for="Mobile" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Profile" class="control-label"></label> <input asp-for="Profile" class="form-control" /> <span asp-validation-for="Profile" class="text-danger"></span> </div> <div class="custom-file"> <label asp-for="Photo" class="control-label"></label> <input asp-for="Photo" class="form-control custom-file-input" id="customFile"> <label class="form-control custom-file-label" for="customFile">Choose file....</label> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { <script> $(document).ready(function () { $('.custom-file-input').on("change", function () { var fileName = $(this).val().split("\\").pop(); $(this).next('.custom-file-label').html(fileName); }); }); </script> }
Index.cshtml :
@model IEnumerable<DotNetCoreRepository.Models.EmployeeModel> @{ ViewData["Title"] = "Index"; } <h5>Index</h5> <p> <a asp-action="AddEmployee">Add New Employee</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.UserName) </th> <th> @Html.DisplayNameFor(model => model.City) </th> <th> @Html.DisplayNameFor(model => model.State) </th> <th> @Html.DisplayNameFor(model => model.Mobile) </th> <th> @Html.DisplayNameFor(model => model.Profile) </th> <th> @Html.DisplayNameFor(model => model.ProfileImage) </th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.UserName) </td> <td> @Html.DisplayFor(modelItem => item.City) </td> <td> @Html.DisplayFor(modelItem => item.State) </td> <td> @Html.DisplayFor(modelItem => item.Mobile) </td> <td> @Html.DisplayFor(modelItem => item.Profile) </td> <td> <img src="~/images/@item?.ProfileImage" class="rounded-circle" height="40" width="70" asp-append-version="true" /> </td> </tr> } </tbody> </table>
Step 8: Add controller code
public class HomeController : Controller { private readonly IEmployeeRepository _employeeRepository; private readonly IWebHostEnvironment WebHostEnvironment; public HomeController(IEmployeeRepository employeeRepository, IWebHostEnvironment webHostEnvironment) { _employeeRepository = employeeRepository; WebHostEnvironment = webHostEnvironment; } public IActionResult Index() { return View(_employeeRepository.GetAllEmployee()); } public IActionResult AddEmployee() { return View(); } [HttpPost] public IActionResult AddEmployee(EmployeeViewModel em) { string uniuefilename = string.Empty; if (em?.Photo != null) { string folderpath =Path.Combine(WebHostEnvironment.WebRootPath ,"images"); uniuefilename = Guid.NewGuid() + "_" + em?.Photo?.FileName?.Split("\\").LastOrDefault() ; string FilePath= Path.Combine(folderpath,uniuefilename); em.Photo.CopyTo(new FileStream (FilePath,FileMode.Create)); } EmployeeModel emp = new EmployeeModel(); emp.UserName = em.UserName; emp.State = em.State; emp.City = em.City; emp.Mobile = em.Mobile; emp.Profile = em.Profile; emp.ProfileImage = uniuefilename; _employeeRepository.AddUpdateEmployee(emp); return RedirectToAction("Index"); } }
Note : we have added here images forlder inside wwwroot folder for storing images
Now project setup is ready to run by clicking on iis express or pressing F5.
Screenshot :
ScreenShot 2: File(Image) Upload in ASP.NET Core MVC with Example
Summary :
In this tutorial we have implemented File(Image) Upload in ASP.NET Core MVC with Example
I hope this tutorial will help you. If you have any doubts reguarding File(Image) Upload in ASP.NET Core MVC with Exampleplease ask your doubts or query in the comment section, Also Please put your feedback on comment section which helps me to improve for upcomming tutorial. And If you like this post then please share it with your friends.
Also Learn More Tutorial :
- ASP.Net Core: Form Submit (Post) with Example
- File(Image) Upload in ASP.NET Core MVC with Example
- .Net Core: Read Connection String from AppSettings.json file
- CRUD Operation Using Asp.Net Core Mvc with Repository Pattern
- Display Data in GridView(Grid) Using ASP.Net Core MVC
- Asp.Net Core: DbContext In EntityFramework core
- Difference between AddSingleton vs AddScoped vs AddTransient in asp.net core
- Difference between .NET Core and .NET Framework
- Difference between TempData keep() And Peek() in Asp.Net MVC
- Asp.Net Image Upload in 3-Tier Architecture and store in sql database
5 Comments