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
4

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How is this array structured in $_FILES?
Do a print_r($_FILES['userfile]); and check. Don't have the code in front of me.
@PhilipLisitsyn Did it solve your problem? If yes, feel free to accept it and if no, please let me know what happened.

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.