0

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);

                }
            });
        });

1 Answer 1

1

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++;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.