File upload in ASP.NET Core MVC (Storing in Folder)

In this Part, we are going to learn how to upload files and store in a folder in ASP.NET Core MVC in a step by step way.

  • Creating ASP.NET Core Application
  • Adding Controller
  • Adding View
  • Adding Images Folder to Store Uploaded Images
  • Adding Index Action Method to Handle POST Request
  • Uploading Image
  • Output

We are going to create ASP.NET Core Web Application for that we are going to choose ASP.NET Core Web Application template.

Creating ASP.NET Core Application

Next, we are going to set Project Name WebApplication12 and location and in last part, we are going to choose .Net Core framework and ASP.NET Core Version 3.0 as the framework for application and few advance settings for such as configuring https and enabling docker we are not going to enable docker settings for this project.

Now finally click on create button to create a project.
Project structure
The project structure generated according to the configuration.

After creating a project, the next step we are going to add a controller.

Adding Controller

We are going to add a controller with Name Demo Controller after adding controller we have default Index action method in it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication12.Controllers
{
    public class DemoController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

After adding Demo Controller and Index Action Method next we are going Add Index View.

Adding View

For Adding View just by right-clicking inside Index Action Method and from the list choose Add View option a new dialogue pops up which has View Name same as Action Method Name Index next we are not going to select Template and Model class for this View click on Add button to create View.

After Creating Index View Next, we are going to add Form tag with the encoding type “multipart/form-data” and set Controller and Action which handle Post Request an inside form tag we are going to add file input control and submit button (Upload).

Code Snippet

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>
<div class="row">
    <div class="col-md-5">
        <form method="post" enctype="multipart/form-data" asp-controller="Demo" asp-action="Index">
            <div class="form-group">
                <div class="col-md-10">
                    <p>Upload file</p>
                    <input class="form-control" name="files" type="file" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-10">
                    <input class="btn btn-success" type="submit" value="Upload" />
                </div>
            </div>
        </form>
    </div>
</div> 

Now Let’s Save and Run the application and See How Index View is rendered with Controls.

After creating Index View, we are going to Add Folder with name Images in wwwroot folder to store files in it.
Adding Images Folder to Store Uploaded Images

Adding Index Action Method to Handle POST Request

Next, we are going to Add Another Action Method with name Index which handle POST request and take IFormFile as an input parameter.

Note: – IFormFile interface contains all properties of the file which is posted such as Length, ContentType, Filename.

Index Action Method Which takes IformFile as input in which IformFile interface contains Properties of the Posted file. Next step we are going to valid Length of the posted file if it is greater then zero then we are going generate new file name and also generate a path to store the file in the folder.

Code Snippet

[HttpPost]
 public IActionResult Index(IFormFile files)
 {
     if (files != null)
     {
             if (files.Length > 0)
             {
                 //Getting FileName
                 var fileName = Path.GetFileName(files.FileName);

                 //Assigning Unique Filename (Guid)
                 var myUniqueFileName = Convert.ToString(Guid.NewGuid());

                 //Getting file Extension
                 var fileExtension = Path.GetExtension(fileName);
             
                 // concatenating  FileName + FileExtension
                 var newFileName = String.Concat(myUniqueFileName, fileExtension);

                 // Combines two strings into a path.
        var filepath = 
new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")).Root + $@"\{newFileName}";

                 using (FileStream fs = System.IO.File.Create(filepath))
                 {
                     files.CopyTo(fs);
                     fs.Flush();
                 }
          }
     }
     return View();
 }

After completed with adding Index Action Method next, we are going to Run Application and Test it by uploading an image.

Uploading Image

Output

An image which we have uploaded got uploaded in Images Folder.

By