Q:

Uploading multiple files using formData()

var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "uph.php");
xhr.send(fd);

uph.php:
var_dump($_FILES['fileToUpload']);

This works, but obviously for the files[0] only.  How to get this working for chosen file? 
I tried removing the [0], but it didn't work. 

A:

You have to get the files length to append in JS and then send it via AJAX request as below
//JavaScript 
var ins = document.getElementById('fileToUpload').files.length;
for (var x = 0; x < ins; x++) {
    fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}

//PHP
$count = count($_FILES['fileToUpload']['name']);
for ($i = 0; $i < $count; $i++) {
    echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'<br/>';
}

A:

The way to go with javascript:
var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('file', file);
});

$.ajax({
    type: 'POST',
    url: '/your/url',
    cache: false,
    contentType: false,
    processData: false,
    data : data,
    success: function(result){
        console.log(result);
    },
    error: function(err){
        console.log(err);
    }
})

If you call data.append('file', file) multiple times your request will contain an array of your files. 
From MDN web docs:

"The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. 
The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values." 

Myself using node.js and multipart handler middleware multer get the data as follows:
router.post('/trip/save', upload.array('file', 10), function(req, res){
    // Your array of files is in req.files
}

A:

You just have to use fileToUpload[] instead of fileToUpload :
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[0]);

And it will return an array with multiple names, sizes, etc...

