How to upload multiple files in Asp.net MVC ?


MultipleFile

There are so many ways to do this task in asp.net MVC. But this is one of the easiest ways to upload multiple file.
In this approach we are using Html 5.0 fileupload control. If the browser will not support HTML 5 then it will display in traditional ways.

Step1: Create the blank asp.net mvc application and write the UI code in index view like this


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div id="multiple">
        <input type="file" class="multiple" name="files" multiple />
    </div>
    <div id="single">
        <input type="file" class="single" name="files" /><br />
        <input type="file" class="single" name="files" /><br />
        <input type="file" class="single" name="files" /><br />
    </div>
    <button class="btn btn-default">Upload</button>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

    <script type="text/javascript">
        $(function () {
            if(window.FileReader != null){
                $('#single').hide();
                $('.single').prop('disabled', true);
            } else {
                $('#multiple').hide();
                $('.multiple').prop('disabled', true);
            }
        });
    </script>

Note: If the browser doesn’t support html 5 then this jquery script code will activate Single fileupload option.

Step 2: Write the code in Home controller for file upload like this given below



using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace MultipleFileUpload.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    file.SaveAs(Path.Combine(Server.MapPath("/Images"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
                }
            }
            return View("Index");
        }
    }
}

Summary: We show that how to upload multiple file in asp.net MVC.