ASP.NET Core MVC Image Upload and Retrieve - CodAffection

ASP.NET Core MVC Image Upload and Retrieve

Image upload and retrieve in asp.net core mvc

Images are unavoidable in almost all applications. Previously we have implemented CRUD operation with a normal form without a file to upload. When we’ve got a form with a file uploader, there are few additional procedures. So let’s look at how to upload and retrieve images in ASP.NET Core MVC.

Sub-topics discussed :

  • Design MVC Form to upload an Image
  • Handle Image Form Submit
    • Save the image to the server file.
  • Retrieve uploaded back to the view.
  • Delete image record and file.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). Select Asp.Net Core Web Application template.

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. A new window will be opened as follows, Select Web Application(MVC) and uncheck HTTPS Configuration. The above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Define Model Class

Let’s create a database using Entity Framework Core. For that, we’ve to install corresponding NuGet Packages. So right-click on the project from Solution Explorer, select Manage NuGet Packages, From Browse Tab– search and install respective following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now, let’s define DB model class ImageModel in a new folder – Models.

Apart from the Primary Key, we have columns Title and ImageName. ImageName is used to save the name of the image. IFormFile property ImageFile is a NotMapped property, meaning  there won’t a corresponding table column in the database, just used to receive the posted image file during form submission like a view-model property.

Setup Database

Now let’s define DbContext class ImageDbContext for creating and managing the Database.

As per the above DbContext class, after the DB migration, there will be a table – Images to save records corresponding to the model class ImageModel. In order to interact with the DB, we need an instance of the DbContext class ImageDbContext. For that, we’ll be using ASP.NET Core dependency injection in a bit.

Before that let’s talk about the class constructor parameter options of the type DbContextOptions,Into this options parameter we’ve to pass following informations.

  • Database Provider: Specify the database that we want to use, whether it is SQL Server or MySQL etc.
  • Location of Database: Connection string to the database that we want create.

Let’s save the connection string in appsettings.json file.

Now let me show you how to create an instance of DbContext with dependency injection. Just update Startup class method ConfigureServices as shown below.

Here we’ve called the AddDbContext method, to inject an instance of PaymentDetailContext. Here, to set SQL Server as the DbProvider, UseSqlServer function is called with the above connection string. How does this dependency injection work? that we can discuss once we create an MVC controller.

We’ve done everything for Database, Now let’s do the migration. For that select project from solution explorer, then go to Tools > NuGet Package Manager > Package Manager Console. then execute following commands one by one.


Add-Migration "InitialCreate"
Update-Database

After successful migration, As per the connection string, new Database ImageDB will be created with a new table Images corresponding to the model class.

Create MVC Image Controller with CRUD Actions

To update and retrieve images, let’s create an MVC controller. right-click on Controllers folder Add > Controller, Select ‘MVC controller with views using Entity Framework’ template. ImageController will be created with ImageModel and ImageDbContext.

showing options while creating Image Controller

With the help of Scaffolding Mechanism, new controller will be created with necessary action methods for all CRUD Operations.

Now let’s discuss how ASP.NET Core dependency injection helps this controller for interacting with DB. This ImageController constructor has a parameter of the ImageDbContext (which is _context), ASP.NET Core will automatically inject the same class instance into the parameter as its value. We don’t have to create an instance of the context in each of the MVC controllers when the controller has a constructor parameter of the type ImageDbContext. Now rest of the action methods could interact with the DB using this injected DbContext.

In above controller, we have shown action methods required for demonstrating image upload. there are other action methods too, but not used in this project. Let’s open this project inside your browser, go to Debug > Start without Debugging.

Now if you navigate the URL: /Image/Create, you could see a form with input controls corresponding to each model properties except for ImageFile. so we have to replace ImageName input controls with an image/file uploader corresponding to ImageFile property. After all, Create.cshtml should look like this.

With the accept attribute, we’ve restricted the uploader only for image files. If there is a file uploaded in our form, we’ve to set the form attribute enctype as multipart/form-data’. If you reload the page, you could see the new form like this.

image showing MVC form for image upload

This form will be submitted to the Create action method of the type POST. there also we’ve to make some changes as shown below.

As you know, this is the meat of this article. Into the action method, we’ve bound model properties – ImageId, Title and ImageFile(not ImageName).

First of all, we save the image into wwwroot/Image folder. To do that we need the physical path up to wwwroot folder, for that we injected IWebHostEnvironment property like our DbContext. A unique custom name for the image file is generated to avoid duplicate image files. Using FileStream object, then we can save the image to the images folder with the custom name.

As a second step, we insert image detail with the custom image-name into the DB. Now you could try to upload an image once you rebuild the solution.

After successfully completed with image upload, you will be re-directed to the index view. where inserted records will be listed from the Database table – Images.

Retrieve and Delete Image

If you click on ‘Delete’ hyperlink, Delete view will be opened by showing corresponding record details. In order to show the uploaded image back in the view, we’ve to make a few changes in Views/Image/Delete.cshtml.

The main aim of the view is to confirm the delete operation. with img control attribute src attribute, retrieved image relative path is used. To append the base path, we can set the attribute asp-append-version as true.

Image showing retrieved image details for delete operation

If you confirm this delete operation, it will reach up to the DeleteConfirmed action method of the type POST. by default, it has programmed to delete the corresponding record. Along with that, we’ve to delete the corresponding image file from the ‘image’ folder. for that, we can update the action method.

That’s all about Image Upload and Retrieve in ASP.NET Core MVC. If you want to implement the rest of the CRUD Operation – Edit, you could check out this article – ASP.NET Core MVC CRUD with Entity Framework. The following discussions might help you to extend your application.

Video Tutorial

In our YouTube channel, we have discussed the same topic.

Scroll to Top
9 Shares
9 Shares
Share via
Copy link