HTML5 Multiple File Upload and ASP.Net MVC Ajax

Need to post multiple files via a form asynchronously? Here’s what you need:

1. The standard Jquery library.

2. The following markup. i.e.

a. Html 5 upload control and

b. a mvc hidden field to store a comma delimitated string of the filenames.

i. Note the comma delimitated hidden field exists for the actual committing of the file names to the database which would ideally happen upon saving the whole form(not covered here)

<div class='inp-wrap large'>                         

      <input type='file' name='files' id='file1' multiple />

      @Html.HiddenFor(m => m.CommaFileList, new{data_files='true'})

div>

3. The following javascript for creating the asynchronous call to the mvc action and then updating the page to show the uploaded images. 

$(function () {

var ajaxFormSubmit = function () {

 

            if ($(this).val() == '')

                return false;

            var formdata = new FormData();   

            for (var i = 0; i < this.files.length; i++) {

                var file = this.files[i];

                formdata.append('files', file);                       }

 

            var parentElement = $(this).closest('div');

 

            var $form = $('form');

            console.log('form', $form);

 

            var options = {

                url: '/Profile/Upload',

                data: formdata,

                contentType: false,

                processData: false,

                cache: false,

                type: 'POST',

                error: function (xhr, ajaxOptions, thrownError) {//handle errors here.}

            };

 

            $.ajax(options).done(function (data) {

                $.each(data, function(index, f) {

                    $('img', parentElement).remove();

                });

 

                $('input[data-files]', parentElement).val('');

                $.each(data, function (index, f) {

                    console.log('loop', index, f);

                    $('input[data-files]', parentElement).val($('input[data-files]', parentElement).val()+f+',');

                    $(parentElement).prepend('

+ '/Content/upload/profile/' + f + '' />

);

 

                });

                //chop last comma

                var str = $('input[data-files]', parentElement).val();

                str.substring(0, str.length - 1);

                $('input[data-files]', parentElement).val(str);

            });

            return false;

        };

 

        $('input[type=file]').on('change', ajaxFormSubmit);

});

4. Lastly a MVC action is required to upload the files and return the filenames as a Json list of strings. 

public class ProfileController : BaseController

{

public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)

        {

            var result = new List<string>();

            foreach (HttpPostedFileBase file in files)

            {

                     //.. standard file upload code

                     var fileNm =

                     result.Add(fileNm);

            }

            return Json(result);

        }

}