Multiple file upload with asp.net mvc and HTML5Few days I have written a blog post about Multiple file upload with asp.net 4.5 and Visual studio 2012. It was greatly appreciated by the community and also been part of www.asp.net community daily spot light. On that post one of my reader Ciwan Kurd has requested the asp.net mvc version of that post. So in this post I will explain how we can do multiple file upload with HTML5.
For this post I am going to use asp.net mvc 3 with HTML5 template and visual studio 2012 but you can use same techniques in any version of asp.net mvc. First things we needs to do create a HTML form for the uploading file in asp.net mvc view so following is a code for that.
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="files" value="" multiple="multiple"/>
<input type="submit" value="Upload Image" />
}
In above code that I have use @HTML.BeginForm to create a HTML form with multipart as this attribute is required to upload any kind of files on the server. I have mapped that form to upload action result. Also I have used the file input control with HTML5 multiple attribute which allow us to upload multiple files on the server. Now its time to write code in asp.net mvc controller. Following is a code for that.
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
So, Here you can see we will get the files as HttpPostedFileBase array so I have written a foreach loop to upload the file. On the successful upload it will get back to home page. So let’s run that in browser.
Now once you click on choose files at that time it will allow you select multiple files like following.
Now once you select files and click upload files. It will upload files in app_data folder.That’s it. Hope you like it. Stay tuned for more. Till than happy programming.