So i'm working on a little project, and for the last couple of hours i have tried to find out how to upload multiple files with, formData Obj via AJAX to a PHP server.
I figured it would be pretty easy since i got it working pretty easy with when uploading one file, but when i want to add multiple files to the formData Obj i get all kind of errors.
My Current Code:
HTMN/AJAX::
formData = new FormData($('#form')[0]);
formData.append("File", $("#myFile1")[0].files[0]);
$.ajax({
url: '../uploadFile.php',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json'
}).fail(function(jqXHR) {
console.log(jqXHR.responseText);
console.log(jqXHR.status);
});
}
PHP:
echo $_FILES['File']['name'];
{Lots of code, not worth pasting - my point is that, its working!}
The code above works great, and im able to get everything i need - and upload the file to the a path of my choosing. But the second i try to .append another file it crashes. If i do like the code below it crashes and, throws errors with undefined index
formData.append("File1", $("#myFile1")[0].files[0]);
formData.append("File2", $("#myFile2")[0].files[0]);
Figured i would try to push append it into the same array like this;
formData.append("File[]", $("#myFile1")[0].files[0]);
formData.append("File[]", $("#myFile2")[0].files[0]);
and again it seems to work great, as long as I'm only doing it with one file, but the second i push a another file into the myFile[] array it throws undefined index errors. For me it seems like I'm breaking the formData obj, when i append more then one file - for some reason.
A solution to my problem is running multiple AJAX calls, with every AJAX call uploading one file - but seems like a really inefficient solution. So if anybody could help me out i would appreciate it!