ASP.NET MVC Tutorials

Multiple File Upload in ASP.NET MVC

I have showed you so many articles for uploading files in asp.net how to upload file by using fileupload control. Now I will tell you how you can upload Multiple file upload with asp.net mvc and HTML5 and C#.net.
Now for this article first we will create a new mvc application and add new controller and now create view for the controller action. After creating the action view add the blow code
@{
    ViewBag.Title = "Multiple file upload with asp.net mvc and HTML5" ;
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <h3>Multiple file upload with asp.net MVCc/MVC3/MVC4/MVC5, C# and HTML5 </h3>
    <input type="file" name="files" value="" multiple="multiple"/>
    <input type="submit" value="Upload You Image"  title="Uplad"/>
    <div style="color:Red;font-size:14px">@ViewBag.Message</div>
}
Now add the below code in you action post method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ProjectDemo_MVC.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// Multiple file upload with asp.net mvc and HTML5
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// Post method for uploading files
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase[] files)
        {
            try
            {
                /*Lopp for multiple files*/
                foreach (HttpPostedFileBase file in files)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    /*Saving the file in server folder*/
                    file.SaveAs(Server.MapPath("~/Images/" + filename));
                    string filepathtosave = "Images/" + filename;
                    /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                }
                ViewBag.Message = "File Uploaded successfully.";
            }
            catch
            {
                ViewBag.Message = "Error while uploading the files.";
            }
            return View();
        }
    }
}
After adding code we will add an images folder where uploaded files will save.
 Now run the page. You will get output as shown below
Now select the images to upload
Now click on upload button to upload the files. In your controller you will see the collection of all the files which you you have uploaded.
Now final screen with success message.
Image
now check the Images folder which you have created. 
;