Let’s look, how ASP.NET Core MVC image upload and retrive can be done.
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).
From New Project window, Select Asp.Net Core Web Application.
Once you provide the project name and location. A new window will be opened as follows, Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this project. For that we’ll be using Entity Framework Core. So we’ve to install corresponding NuGet Packages. Right click on Project Name from Solution Explorer, Click on Manage NuGet Packages, In Browse Tab– install following 3 packages. Select package version same as that of your ASP.NET Core.
Now, let’s define DB model class file (https://m2c6a4u3.stackpathcdn.com/Models/ImageModel.cs) in a new folder – Models.
Apart from the Primary Key, we have columns Title and ImageName. ImageName is used to save custom name generated while saving the image in server. IFormFile property ImageFile is a NotMapped property, meaning carry the posted image file in form submission like a view-model property.
Now let’s define DbContext class file- /Models/ImageDbContext.cs.
As per the above DbContext class, after DB migration there will be a table – Images . Into the class constructor, we’ve to pass the Database Provider ( SQL Server, MySQL, Postgre SQL, etc) and corresponding DB connection string. For that update startup.cs file as below.
Here we’ve used Dependency Injection in ASP.NET Core by passing SQL Server as the provider along with the DB connection string from appsettings.json. Now save the connection string in appsettings.json.
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.
After successful migration, As per the connection string, new Database – ImageDB will be created with Images table. Also there will be new Migrations folder in Solution Explorer with corresponding C# files.
Create MVC Image Controller with CRUD Actions
To update and retrieve images, I will create an MVC controller. right click on Controllers folder Add > Controller, Select MVC controller with views using Entity Framework.
With the help of Scaffolding Mechanism, new controller will be created.
For this controller constructor parameter context of the type ImageDbContext, value/ instance will be passed from Dependency Injection. 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.
If you navigate into this 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 controls with image uploader with ImageFile property. so let’s update the view file: /Views/Image/Create.cshtml
You could see the input control for ImageFile. With the accept attribute, we’ve configured the uploader only for image files. since we’ve an uploader inside the form, we’ve to set form attribute enctype as ‘multipart/form-data’. If you reload the page, you could see the new form like this.
This form will be submitted to the Create action method of the type – POST. there also we’ve to make some changes as below.
As you know, this is the meet of this article. Into this method, we’ve bound model properties – ImageId, Title and ImageFile (not ImageName)
First of all, we save the image into wwwroot/Image. to do that we need the physical path to wwwroot, for the we inject IWebHostEnvironment property. a custom name for the image file is generated to avoid duplicate image files. Using FileStream object, we can save the image to the images folder.
As a second step, we save image detail with the custom image-name into the DB. Now you could try to upload this image upload feature once you rebuild this solution.
After successfully completed with image upload, you will be re-directed to the index view. where inserted records will 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 uploaded image back, we’ve to make a few changes in Views/Image/Delete.cshtml.
Actually it is asking for confirmation to delete the record. with img control, we are displaying the uploaded image back. with src attribute, we can provide relative path. To append the base path, we can set the attribute asp-append-version as true.
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 corresponding record. Along with that we’ve to delete corresponding image file from image folder. for that we can update action method.
That’s all about Image Upload and Retrieve in ASP.NET Core MVC. If you want to implement rest of the CRUD Operation – Edit, you could check out this article – ASP.NET Core MVC CRUD with Entity Framework.
Step by Step Video Tutorial
In our YouTube channel, we have discussed the same topic.