user3238663
user3238663

Reputation: 31

formData - AJAX - PHP- Uploading multiple files

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!

Upvotes: 2

Views: 7100

Answers (2)

James Walker
James Walker

Reputation: 411

For pure Javascript use this method
The HTML

<form type="multipart/form-data" >
  File 1: <input id="file1" name="file1" type="file" /><br />
  File 2: <input id="file2" name="file2" type="file" /><br />
          <br />
 <input type="submit" value="Submit" onclick="your_function();" />
</form>

The Javascript:

function your_function(){
    var file1 = _("file1").files[0];
    var file2 = _("file2").files[0];
  var formdata = new FormData();
formdata.append("file1", file1);
formdata.append("file2", file2);
  var ajax = new XMLHttpRequest();
   ajax.open("POST", "path-to-your.php");
    hr.onreadystatechange = function() {
        if(ajax.readyState == 4 && ajax.status == 200) {
                    alert(ajax.responseText);
                /*do what you wish here */
        }
    }
    ajax.send(formdata);
}

The PHP

<?php
echo $_FILES['file1']['title'];
echo $_FILES['file2']['title'];
?>

Hope this helps somebody.

Upvotes: 0

C3roe
C3roe

Reputation: 96151

formData.append("File1", $("#myFile1")[0].files[0]);
formData.append("File2", $("#myFile2")[0].files[0]);

With this approach, did you adapt the PHP part

echo $_FILES['File']['name'];

accordingly …? Otherwise, of course you will get an “undefined index” error.

formData.append("File[]", $("#myFile1")[0].files[0]);
formData.append("File[]", $("#myFile2")[0].files[0]);

This can’t work, because

FormData.append():
Appends a key/value pair to the FormData object.

– and for JavaScript, File[] is just a string with no correlation to any array, so your second line will overwrite the first one in your FormData object.

But you can specify the array index yourself,

formData.append("File[0]", $("#myFile1")[0].files[0]);
formData.append("File[1]", $("#myFile2")[0].files[0]);

— this should work, and give you an array of uploaded files in your PHP script.
To verify, make a var_dump($_FILES); at the beginning of your receiving script.

Upvotes: 4

Related Questions