Aug 19

Uploading Multiple Files in ASP.NET MVC 5

So as I was working on the Direct Sales CRM application, I came to the part where I needed to upload CSV files to be imported / processed.

From the early days of webforms, I recalled this being quite a pain in the neck.

And, honestly, I wasn’t looking forward to figuring out how to make it work in MVC.

But, boy was I worrying about nothing. NOTHING.

It was so stupid simple, I had it completely implemented, including saving a reference record of the file to the database, in a matter of a few hours.

The following code is a verbatim copy from http://www.aspdotnet-pools.com/. Not that anything will happen to it, but I’m a digital hoarder and would also like a place for me to reference in the event something changes on their end.

Here is the code for the View:

@{
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 multiple="multiple" name="files" type="file" value="" />
<input title="Uplad" type="submit" value="Upload You Image" />
<div style="color: red; font-size: 14px;">@ViewBag.Message</div>
}

And here is the code for the Controller

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();
        }

    }
}

I hope it’s as easy for you to implement as it was for me.

I look forward to these other little gems that I’ll find.

Code On!
RJ