Upload multiple files using AJAX- ASP.NET MVC (multiple file input with same class)

This technique is used to upload multiple files/photos by using multiple file input control (dynamically added), AJAX and ASP.NET-

1. Multiple file input control (with same .class)
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

HTML Part
----------------------------------------

<div class="form-group">
    <input class="multiplephoto" type="file" name="files" multiple />
</div>

<button id="AddMorePhoto">Add more photo </button>
Adding another file input
-----------------------------------------

 $('#AddMorePhoto').on('click', function (e) {
         e.preventDefault();
         $('<div/>').addClass('form-group')
         .html($('<input class="button multiplephoto" type="file" name="files" multiple />'))
         .insertBefore(this);

 });


Submitting the form as FormData via AJAX
-----------------------------------------

var fd = new FormData();

//append some other data to fd. i.e.-
fd.append('PersonName', personName);

var inputs = $('.multiplephoto');
$.each(inputs, function (obj, v) {
    var file = v.files[0];
    fd.append("photos", file);
    //var filename = $(v).attr("data-filename");
});

$.ajax({
    url: "/ControllerName/ActionMethodName",
    type: "POST",
    data: fd,
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    beforeSend: function () {
    },
    success: function (response) {
    },
    error: function (request, status, error) {
    },
    complete: function () {
    }

});
Server-side code
------------------------------------

[HttpPost]
public JsonResult GetPhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    var directory = HttpContext.Server.MapPath("~/Photos");
                
    foreach (var file in photos)
    {
        String fileName = file.FileName;
        string imagePath = Path.Combine(directory, "LoginPhotos", fileName);
        file.SaveAs(imagePath);
    }

    return Json("success");

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s