Skip to content

Upload and Save an Image in ASP.NET Core MVC

Problem definition: When the form data is inserted, the image must be uploaded to a local folder, saved in the database and previewed in the form. Below are screenshots of inserting an image into the database and listing it on the Index page.

Create item form with image upload and preview
Item list page showing the uploaded image for each item

Implementation: To implement image saving, follow the steps below.

  • Create a model class for items.
  • Create a controller named Items.
  • Create an action method named CreateItem inside the controller.
  • Create a separate method named UploadImage that returns the image path.
  • Create a JavaScript file named item.js that previews the image in the img tag.
  • Add this Item model class to the DbContext class and then run the migration commands.
  • Add the view for the CreateItem action method.
  • Create an action method named Index to list the items
  • Create a view for the Index method.

In the implementation phase, we create a model class for items. Below is the code for the 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 named demoDBcontext and add the DbSet below. It generates the table in the database when you run the migration commands.

public DbSet<Item> Items { get; set; }

Now create a controller named Items and write the action methods below in it. CreateItem() is the POST method that saves the model data to the database.
UploadImage() gets the image folder in wwwroot from IWebHostEnvironment, makes the file name unique and saves the image in the local image folder that we created inside wwwroot.
Index() fetches the list of records from the database and shows it in 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, write the code below, and add a reference to the JavaScript file in the CreateItem view.

Razor view code for the CreateItem form with image upload

Now create a JavaScript file named item.js and write the code below. It shows a 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. You can save the image to the database and preview it.

List of Items to present into grid: We implemented an action method, Index, that retrieves the item records from the database table into a list and returns them to the view. Below is the code for the controller action method.

public IActionResult Index()

       {

           var data = _db.Items.ToList();

           return View(data);

       }
Razor view code for the item list page