0

Im using single file input field with multiple upload property. I've already tested single file pass like that and it worked. Now I'm trying to pass files using an array but there is a mistake. There is no form.

HTML:

<input id="fileInfo" name="userfile[]" type="file" multiple>

JS:

var formData = new FormData();
var files = [];
for(var i = 0; i < length; i++) {
    files[i] = $('input', '#fileInfo')[0].files[i];
}
formData.append('userfile', files);
$.ajax({
    url: "example.php",
    data: formData,
    type: 'POST',
    dataType: 'json',
    processData: false,
    contentType: false,
    success: function(res)
    {
        console.log("done");
    }
});

PHP:

<?php
$length = sizeof($_FILES['userfile']['name']);
json_encode(array($length));

error.log:

PHP Notice:  Undefined index: userfile in /path/to/php on line 2, referer: http://localhost/test

1 Answers1

6

Instead of building an array with the files (which is kind of strange to do since the source already is an array), append the files directly to your FormData object:

var formData = new FormData();

// Get all the files so we easily can get the length etc.
// Not necessary, but it will make the code easier to read.
var files = $('input', '#fileInfo')[0].files;

for(var i = 0; i < files.length; i++) {
    formData.append('userfile[]', files[i]);
}

$.ajax({
    // your ajax call
});

We've also changed 'userfile' to 'userfile[]' which will make it an array that you can loop through in your PHP.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40