Upload Image and Display Preview in Asp.Net Core 8 MVC Using C#.Net

Simple tutorial with example to upload image in wwwroot folder and display the preview of uploaded image in view using asp.net core mvc 8 by C#.Net.
In today's article I will show you a simple tutorial with example to upload an image file and display preview in asp.net core mvc using c#.net by using model class property and IFormFile . Here I have used input file control to browse the file and will capture the uploaded file in controller in IFormFile interface at controller on submit. Here we will upload image file in wwwroot folder in asp.net core mvc application.

Now for show sample tutorial to with an example we will create a new asp.net core mvc application using c#.net. In this article I have used asp.net core 8 mvc. After creating the asp.net core 8 mvc application add a model class file and add the below code.
public class FileModel
{      
    public IFormFile File { get; set; }
    public string FilePath { get; set; }
}
In above code I have defined 2 propertied first of type IFormFile  and second one is of type string. So, the property of type IFormFile  will use to capture the uploaded file detail at the controller end of HttpPost IActionResult method and second one is used to pass the uploaded file path to view and bind it to image control to display the preview.

After adding the model class file, we will add a folder in the wwwroot folder. In this folder we will upload the file and then by passing the uploaded file path to view we will display the uploaded image preview.

Folder in wwwroot

Now let's add a controller class file. In this controller class file, we will add a HttpGet method of return type IActionResult. 
 [HttpGet]
public IActionResult Index()
{
    FileModel fileModel = new FileModel();
    return View(fileModel);
} 
In above IActionResult methos i have created the object of model class and pass it to View. Now we will create the view and add the below code. 
 @model FileModel
@{
    ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    <div style="color:red">@ViewBag.Message </div>
    <div style="font-weight:bold;">Select File:</div>
    <div>
        <input type="file" class="form-control" name="file" />
    </div>
    <br />
    <div><input type="submit" value="Upload File" /></div>
     <b>FILE PREVIEW</b>
    <div style="color:brown">
        <img src="@Model.FilePath" width="200px" height="200px" />
    </div>

} 
In above code i have added the refrence of the mode class. After adding the model class refrence I have added the form tag by using Html.BeginForm. In this the action name controller name and the formmethod type as post have been passed.   

In this I have added "@enctype = "multipart/form-data". This is the most important piece of the view code. If we don't add this attribute on click on submit button, we will not get the uploaded file detail at controller end. Here enctype describe the encode type of the form data when user post the data to server.

ViewBag have been used to display the message. Here input control of type file have been used, this will help user to select or browse the file. In this the most important thing ius the name of the input control. In current case is name="file". Here the name of the input control name and the model class property of type IFormFile variable name should be same. If there is any difference on that case, you will not be able to get the uploaded file detail at controller end on submit or post of the form.

Here I have used img control to display the review of the uploaded file. Here I have assign the Model property @Model.FilePath to add provide the path of the uploaded image file. 
 [HttpPost]
public IActionResult Index(FileModel fileModel)
{
    if (fileModel.File != null)
    {
        try
        {
            string parentPath = @"wwwroot\Demofiles\";
            string uploadfilepath =Path.Combine(Directory.GetCurrentDirectory(), parentPath, fileModel.File.FileName);
            var filestream = new FileStream(uploadfilepath, FileMode.Create);
            fileModel.File.CopyToAsync(filestream);
            string dbSaveUploadPath = string.Format("{0}{1}", @"\Demofiles\", fileModel.File.FileName);
            fileModel.FilePath = dbSaveUploadPath;
            ViewBag.Message = "File uploaded successfully.";
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message;
        }
    }
    else
    {
        ViewBag.Message = "Please select file to upload.";
    }
    return View(fileModel);
} 
In above code I have passed the model class which is named as FileModel is passed as a parameter in HttpPost index method.  In first line of code validation of uploaded file is written. If we get uploaded file as null on that case, we will simply display the user-friendly message to select the file. 

Here I have used Path.Combine to prepare the upload file path as @"wwwroot\Demofiles\". After that I have taken FileStream to prepare the upload file stream instance. in file stream object i have passed the upload file path and the FileMode as Create. This will create the instance of the file on the given path. At the end CopyToAsync to copy the file to the directory. To provide the saved path for file in database. At end user view message have been stored in the ViewBag to display on page to user. Now we have done let's run the code to check the output. and now click on upload button without selecting the file you will get message to select the file.

No file selected in asp.net core mvc file upload

Now let's select the file and click on button.

Upload Image in Asp.Net Core

One we click we will get the uploaded file detail in IFormFile.

IFormFile in Controller

Here we are able to get the uploaded file detail at controller end. Here you can see thee Input file control name and the IFormFile property is same. any difference will cause trouble to get the file in controller. Now let's press F5 and check the final output.

wwwroot Image File

Above showing the uploaded file and below is the output in view.

Uploaded Image File Preview in View in Asp.net Core MVC
upload-image-and-display-preview-in-asp-net-core-8-mvc-using-c-net.zip 3.8MB

Post a Comment