File Upload in Asp.Net Core MVC Using C#.Net

How to Upload file in wwwroot folder in asp.net core 8 mvc using c#.net. Use of IFormFile, FileStream, CopyToAsync to save file & get save path in DB.
In today's article I will show you how you can upload a file in asp.net core mvc using c#.net. Here I have used asp.net core mvc 8. Here I will show you how you can upload a file in wwwroot folder. So, for this article first we need to create an asp.net core mvc application using C#.Net. After creating the asp.net core 8 mvc application we will add a folder in wwwroot folder.  

wwwroot folder in asp.net core mvc

Here I have created a folder named as "DemoFolder". In this folder we will upload the user selected file. To upload the file, we will use input file type of control and input Submit button. 

Now for this article first we will create a new asp.net core mvc application and adda controller. In this controller class file first, we will add a HttpGet IAction method. This HttpGet method will act as page load in your asp.net core mvc application. 

[HttpGet]
public IActionResult Index()
{
    return View();
}
Now we will add a view in the and you need to add few controls like Input file control, Input submit button. 
@{
    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>
}
In above code let's first discuss the form tag. 
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
Here Html.BeginForm methos is used for defining the form tag. In this method we need to add the Action name and the controller name and Form Method Type as Post. This piece of code will define that when user click on submit button which method need to execute at controller end.  Here one of the most important thing which we need to take care new { @enctype = "multipart/form-data" }. If we don't add this html attribute, we will not be able to get the selected file at the controller end. 

I have taken the ViewBag.Message to display the final message. In this input control have been taken of type file. Here we need to take care of one thing the name="file". Name of the file control is used to get the uploaded file detail at controller end. This we will pass as a parameter in the HttpPost method in controller.

Now let's write code to upload the file in the folder.
[HttpPost]
public IActionResult Index(IFormFile file)
{
    try
    {
        string parentPath = @"\wwwroot\DemoFiles\";
        string uploadfilepath = string.Format("{0}{1}{2}", Directory.GetCurrentDirectory(), parentPath, file.FileName);
        var filestream = new FileStream(uploadfilepath, FileMode.Create);
        file.CopyToAsync(filestream);
        string dbSaveUploadPath = string.Format("{0}{1}", @"\DemoFile\", file.FileName);
        ViewBag.Message = "File uploaded successfully.";
    }
    catch (Exception ex)
    {
        ViewBag.Message=ex.Message;
    }
    return View();
}
In above code I have passed IFormFile as a parameter and parameter named as file. Here the parameter name is same as the input file control name. After this I have declared a variable the of string type where I have defined the folder available in the wwwroot folder.  After this I have used string.Format to concatenate the string. Here I have used Directory.GetCurrentDirectory(), folder path and the file extension with file.FileName. Now here I have created object of FileStream. Here I have passed the uploadfilepath and File Model by using FileMode.Create. 

Now CopyToAsync is used to copy the file in the given location. Here i have passed the FileStream object as a parameter to CopyToAsync  method. After that I have declared a variable where I am preparing the path to save in the DB named as dbSaveUploadPath. At the end I have added message to display the message to user. Now let's put a break point and check the output.


File upload control in asp.net core mvc

Now let's select the file.

File Selected in asp.net core mvc
Ones we click on Upload File button our break point will hit, and we will be able to get the selected file detail. 

IFormFile in controller

In above screen shot we are able to get the user selected file detail. Now let's press F5 and check the output.
File Uploaded successfully in asp.net core mvc

After getting success message let's check the file uploaded path. We are able to get the uploaded file. 

File in wwwroot

In above explanation I have made a statement that if we don't put new { @enctype = "multipart/form-data" } html attribute into the form tag we will not be able to get the user selected file at controller end. Let's check ones by removing the new { @enctype = "multipart/form-data" }. Make changes in you form tag as shown below. 
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
After this run the application and check the output.

Null wile uploading file in wwwroot folder

Here in above code, we can see that we are getting null instead of getting file detail. 
Info! Two most impoertant items 1. Input control name and the parameter passed HttpPost method in controller(Eg: name="file" and public IActionResult Index(IFormFile file))
2. In form tag you must include the HTML attribute "new { @enctype = "multipart/form-data" }"
file-upload-in-asp-net-core-mvc-using-c-net.zip 3MB

Post a Comment