Save and Upload Image in Core MVC

Problem Defination :- While inserting the form data Image needs to save the database and upload the image in local folder and preview the image into the form. Below is the screen images for image to insert into database and list it into the Index page.

Image is not available
Image is not available

Implementation :- To implement image save functionality firstly we have to follow below steps.

  • Create a Model Class for items.
  • Create a Controller named it Items.
  • Create a Action Method named it CreateItem inside the controller.
  • Create one differnet methods for getting the imagepath named it as UploadImage.
  • Create a JavaScript file named it as item.js for javascript code to preview image into the img tag.
  • Add these item model class into the DbContext class and then execute the migration commands.
  • Add the View for CreateItem Action Method.
  • Create a Action Method for List the items and named it as Index
  • Create a View for Index method.

In The implemetation phase we will create one model class which is used for Items. Below is the code for Item Model class.

                
 public class Item
    {
        [Key]
        public int ItemId { get; set; }
        public string Name { get; set; }
        public string Brand { get; set; }
        public string Description { get; set; }
        public string Path { get; set; }
        [NotMapped]
        [Display(Name ="Choose Image")]
        public IFormFile ImagePath { get; set; }
    }
                            
                      

Now create a DBContext class and named it as demoDBcontext and add the below one DBSet into this class that will generate the table into the database when you run the migration commands.

                
public DbSet Items { get; set; }
                        
                        

Now Create the Controller with named Items and write the below Action Methods into it. CreateItem() is the post method in which we are saving the model data into database.
UploadImage() is the method is used for getting the image folder for wwwroot from webhostingenviornment and make a file name unique for images and save the images into the local image folder that we have created inside the wwwroot folder.
Index() is the method in which we are fetching the list of records from database and show into the view.

                
 public class ItemsController : Controller
    {
        private readonly AmazonShoppingDBContext _db;
        private readonly IWebHostEnvironment webHostEnvironment;
        public ItemsController(AmazonShoppingDBContext db,IWebHostEnvironment environment)
        {
            _db = db;
            webHostEnvironment = environment;

        }

        public IActionResult Index()
        {
            var data = _db.Items.ToList();
            return View(dataList);
        }
        public IActionResult CreateItem()
        {
            return View();
        }
        [HttpPost]
        public IActionResult CreateItem(Item item)
        {
            string UniqueFileName = UploadImage(item);
            var data = new Item
            {
                Name = item.Name,
                Brand=item.Brand,
                Description =item.Description,
                Path = UniqueFileName,
            };
            _db.Items.Add(data);
            _db.SaveChanges();
            TempData["Success"] = "Data Saved Successfully";
            return RedirectToAction("Index");
        }
        public string UploadImage(Item item)
        {
            string UniqueFileName=string.Empty;
            if(item.ImagePath!=null)
            {
                string ImageFolder = Path.Combine(webHostEnvironment.WebRootPath, "/images/");

               UniqueFileName=Guid.NewGuid().ToString()+"_"+item.ImagePath.FileName;
                string filePath=Path.Combine(ImageFolder,UniqueFileName);
                using(var filestream= new FileStream(filePath,FileMode.Create))
                {
                    item.ImagePath.CopyTo(filestream);
                }
            }
            return UniqueFileName;
        }
}
                            
                        

Now create a View for the CreateItem Action Method and write the below code and add reference of this js file to CreateItem View.

Image is not available

Now create a Javascript file and named as it item.js and write the below code and it provides the preview of the image.

                
$(document).ready(function () {
    $('#ChooseImg').change(function (e) {
        var url = $('#ChooseImg').val();
        var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
        if (ChooseImg.files && ChooseImg.files[0] && (ext == "jpg" || ext == "gif" || ext == "png" || ext == "bmp")) {
            var reader = new FileReader();
            reader.onload = function () {
                var output = document.getElementById('PrevImg');
                output.src = reader.result;
            }
            reader.readAsDataURL(e.target.files[0]);
        }
    });
});
                            
                        

Now run the application it will work and you will be able to save the image into the database and preview the image..

List of Items to present into grid :- We have implemented a action method Index which is retrieving the items record from database table into the list and return to view,below is the code for controller action method.

                    
 public IActionResult Index()
        {
            var data = _db.Items.ToList();
            return View(data);
        }
                            
                        
Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.