Search code examples
javascriptc#jqueryasp.net-mvc-5

Upload multiple files at once using ajax


Check the code below. Here i am trying to upload multiple selected files by user at once but problem is that ajax not sending all selected files. Its just sending first file from selected files. Whats wrong i am doing here?

c# class:

public class AddAssets
    {
        public List<HttpPostedFileBase> my_file { get; set; }
    }

mvc5 method:

[HttpPost]
        public JsonResult mymethod(AddAssets data)
        {

}

Html:

 <div class="modal-body">
                        <input type="file" name="my_file[]" class="theFiles" id="files" multiple>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="Upload">Upload</button>
                    </div>

Jquery:

 $('#Upload').click(function () {

            var form_data = new FormData();
            $.each($(".theFiles"), function (i, obj) {
                $.each(obj.files, function (j, file) {
                    form_data.append('my_file[' + i + ']', file); 
                });

            });



            $.ajax({
                url: '/controller/mymethod',
                dataType: 'text',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function (data) {

                    console.log(data);
                },
                error: function (error) {
                    console.log(error);

                }
            });
        });

Solution

  • Remove dataType: 'text', from $.ajax({.

    When you are appending files you use form_data.append('my_file[' + i+ ']', file);. Here for file name you are using 'my_file[' + i+ ']' which will be same for all files. And it seems to be cause of the issue.

    Use another variable to set file name like index shown below.

    var form_data = new FormData();
    var index = 0;
    $.each($(".theFiles"), function (i, obj) {
        $.each(obj.files, function (j, file) {
            form_data.append('my_file[' + index + ']', file); 
            index++;
        });
    });