How to Upload multiple files in Asp.net Core MVC C#

In this article, we will learn how to Upload multiple files using Asp.Net Core MVC C#. Once submitted multiple files will be saved in a folder directory inside the www folder using For Loop in Asp.net Core MVC.

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here

Also check my previous articles https://labpys.com/how-to-create-crud-operation-in-asp-net-core-mvc-c ,https://labpys.com/how-to-create-login-page-using-asp-net-core-mvc-c-with-database

Create an ASP.NET Core MVC Project

Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.

Enter  project name and click create.

Create Controller

using Asp.netcore_Tutorials.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace Asp.netcore_Tutorials.Controllers
{
    public class HomeController : Controller
    {
         private IWebHostEnvironment _environment;
        public HomeController(IWebHostEnvironment environment)
        {          
            _environment = environment;
        }

        public IActionResult Index()
        {
            return View();
        }
       
        public IActionResult Privacy()
        {
            return View(nameof(Index));
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Now next add another Index Method which handle POST request and take List<IFormFile> as an input parameter.

[HttpPost]
        [AutoValidateAntiforgeryToken]
        public IActionResult Index(List<IFormFile> fromFiles)
        {
            string uploadpath = _environment.WebRootPath;
            string dest_path = Path.Combine(uploadpath, "uploaded_doc");

            if (!Directory.Exists(dest_path))
            {

                Directory.CreateDirectory(dest_path);
            }

            List<string> uploadedFile = new List<string>();

            foreach(IFormFile file in fromFiles)
            {
                string sourcefile = Path.GetFileName(file.FileName);
                using (FileStream filestream = new FileStream(Path.Combine(dest_path, sourcefile),FileMode.Create))
                {
                    file.CopyTo(filestream);
                    uploadedFile.Add(sourcefile);
                    ViewBag.Message += string.Format("<b>{0}</b> Files Uploaded.<br/>", sourcefile);
                }
                    
            } 
            return View();
        }

Customize View Index

A view is Asp.Net Core MVC application is responsible for application data presentation. View is HTML Form which has been created using Razor Tag attribute with the following attribute asp-controller,asp-action.

@{
    ViewData["Title"] = "Home Page";
}

<div class="row">
    <div class="col-5">

        <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
         <div class="form-group">
             <div class="col-md-10">
                 <h3>Upload File</h3>
                    <input class="form-control" name="fromFiles" multiple="multiple" type="file" />
                 </div>
         </div>
         <br/>
            <div class="form-group">
                <div class="col-md-10">
                   
                    <input class="btn btn-primary" type="submit" value="Upload File"   />

                </div>
            </div> 
        </form> 

        <span style="color:brown">@Html.Raw(ViewBag.Message)</span>
    </div> 
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *