Multiple file upload with asp.net mvc and HTML5

Few 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.

Multiple file upload in asp.net mvc with HTML5

Now once you click on choose files at that time it will allow you select multiple files like following.

Multiple file upload in asp.net mvc  and HTMl5

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.

Shout it

kick it on DotNetKicks.com

3 comments:

  1. ViewBag.Message = "File(s) uploaded successfully" won't be displayed if you use RedirectToAction. Instead use "return View("Index");

    __
    John Leme
    Dev at SeguroFacil!

    ReplyDelete

Your feedback are very important to me. Please provide your feedback via putting comments.