How to upload multiple files at once in an MVC form

Posted written by Paul Seal on March 27, 2018 .NET Framework

This post will help you if you need to upload multiple files at once in an MVC form. 

The examples are for an umbraco website, but the principles are the same. 

Model

Create a model

Notice the Files property is an array of HttpPostedFileBase

using System.Web;

namespace MFU.Web.Models
{
    public class UploadModel
    {
        public HttpPostedFileBase[] Files { get; set; }
    }
}

View

Create a partial view, I called mine _UploadForm

Pay attention to the enctype, if you miss this, it won't work.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<UploadModel>

@using MFU.Web.Models

@using (Html.BeginUmbracoForm("SubmitForm", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="Files" id="Files" multiple />
    <button>Submit</button>
}

Call the partial from the main view

@{ Html.RenderPartial("_UploadForm", new MFU.Web.Models.UploadModel()); }

I also added this code to show the names of the files you uploaded.

@if (TempData["FileNames"] != null)
{
    <p>Last uploaded files:</p>
    @Html.Raw(TempData["FileNames"].ToString())
}

Controller

On the form submit you can iterate through the array of files and save them or do whatever you need to. In my example I am just getting the file names to show on the post back.

using System.Web;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
using MFU.Web.Models;
using System.Text;

namespace MFU.Web.Controllers
{
    public class UploadController : SurfaceController
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(UploadModel model)
        {
            if (ModelState.IsValid)
            {
                StringBuilder fileNames = new StringBuilder();
                fileNames.Append("<ul>");
                foreach (HttpPostedFileBase file in model.Files)
                {
                    //You can do something with the files here like save them to disk or upload them into the Umbraco Media section
                    fileNames.Append("<li>");
                    fileNames.Append(file.FileName);
                    fileNames.Append("</li>");
                }
                fileNames.Append("</ul>");
                TempData["FileNames"] = fileNames.ToString();
                return RedirectToCurrentUmbracoPage();
            }
            return CurrentUmbracoPage();
        }
    }
}

Here is the GitHub repo which contains the code.