Multiple File upload in ASP.NET MVC

Download file Sample Project

 

Uploading several files is nice and clean with the help of the FileCollectionModelBinder available in the ASP.NET MVC futures assembly. Please follow the procedure below to create a sample.

  • Add a form to your view with the settings below (you can use the ASP.NET MVC form helpers too to arrive at the same result).
<form method="post" enctype="multipart/form-data" action="/home/uploadfiles">

<div>

<input type="file" name="fileName" id="fileName" accept="file/zip" />

<input type="file" name="fileName" id="file3" accept="file/zip" />
<%=Html.ValidationMessage("fileName") %>

</div>

<div>

<input type="submit" value="Upload file"/>

</div>

</form>
  • Add a reference to the ASP.NET MVC futures assembly. This is available from the ASP.NET MVC project on CodePlex – direct link.
  • In your global.asax file, add a call to FileCollectionModelBinder.RegisterBinder( as shown below
protected void Application_Start()

{

RegisterRoutes(RouteTable.Routes);

FileCollectionModelBinder.RegisterBinder(ModelBinders.Binders);

}
  • Your controller code can then accept a parameter of type HttpPostedFileBase[] as shown below. Please note that the name of the argument to this method should match the ID and Name of the client-side file upload form element.
[AcceptVerbs(HttpVerbs.Post)]

public ActionResult UploadImage(HttpPostedFileBase[] files)

{
// process files here
}

A complete sample is available for download.

In order to upload one file at a time, you do not need the futures assembly. The built-in HttpPostedFileBaseModelBinder can handle this.

Loading