File Upload Multiple via aJax - PHP

5

I'm trying to upload files via ajax and PHP with the following codes below and it's not working. I can not identify what I'm doing wrong.

Page

<div id="bsUpload">
<form action="" method="post" enctype="multipart/form-data">   
    <input type="file" name="fileUpload[]" class="fileUpload"><br>
    <input type="file" name="fileUpload[]" class="fileUpload"><br>
    <input type="file" name="fileUpload[]" class="fileUpload"><br>
    <br>
    <input type="button" name="btEnviar" value="Fazer Upload"> 
</form>       

JavaScript

var $jq = jQuery.noConflict();
$jq(function(){

    var bsUpload = $jq("#bsUpload");

    bsUpload.on('click', 'input[name="btEnviar"]', function(event){
        event.preventDefault();

        formdata = new FormData(this);

        $jq.ajax({
            type: 'POST', cache: false, processData: false, contentType: false, 
            url: 'upload.php', data: formdata,
            success: function(j){
                            alert(j);
                         }
            });
    });

});

PHP

<?php

foreach($_FILES['fileUpload']['error'] as $key => $error){
    if($error == UPLOAD_ERR_OK){
        $name = $_FILES['fileUpload']['name'][$key];
        move_uploaded_file($_FILES['fileUpload']['tmp_name'][$key], '../../upload/'.$name);
    }
}

echo 'Envio OK';

?>

The Error:

  

Notice: Undefined index: fileUpload in C: \ xampp \ htdocs \ examples \ upload-ajax \ TemplateC \ js \ Ajax \ upload.php on line 3

     

Warnig: Invalid argument supplied for foreach () in C: \ xampp \ htdocs \ examples \ upload-ajax \ TemplateC \ js \ Ajax \ upload.php on line 3

It worked out

Thank you for the personal help

    
asked by anonymous 21.01.2015 / 19:36

2 answers

2

The problem is that you create FormData to send but not add any of the files in it and your POST ends up empty.

Here's how you can do it:

var $jq = jQuery.noConflict();
$jq(function(){

    var bsUpload = $jq("#bsUpload");

    bsUpload.on('click', 'input[name="btEnviar"]', function(event){
        event.preventDefault();

        var formdata = new FormData();

        $jq.when($jq('.fileUpload').each(function(i,e) {
            // adiciona uma entrada em "formdata" para cada campos de classe "fileUpload" com arquivo selecionado
            var file = e.files[0];
            if(file)
                formdata.append('fileUpload['+i+']', file);
        })).done(function(){
            $jq.ajax({
                type: 'POST', cache: false, processData: false, contentType: false, 
                url: 'upload.php', data: formdata,
                success: function(j){
                   alert(j);
                }
            });
        });
    });
});

And as @Daniela mentioned, to avoid this kind of error in PHP you should always check if the index actually exists in the array.

Your PHP would look like this:

if (isset($_FILES['fileUpload'])) {
    foreach($_FILES['fileUpload']['error'] as $key => $error){
        if($error == UPLOAD_ERR_OK){
            $name = $_FILES['fileUpload']['name'][$key];
            move_uploaded_file($_FILES['fileUpload']['tmp_name'][$key], '../../upload/'.$name);
        }
    }

    echo 'Envio ok';

} else {
    echo 'Nenhum arquivo enviado';
}

You should add a few more checks in your PHP code to make sure the files were actually uploaded and no errors occurred in the process.

    
21.01.2015 / 20:47
3

The first alert is why you did not check if fileUpload was an index of $_FILES .

<?php    
if (isset($_FILES['fileUpload'])) {

}

The second error occurred because you are trying to iterate $_FILES['fileUpload']['error'] which is not an array, in which case you should use switch .

<?php    
if (isset($_FILES['fileUpload'])) {
    switch ($_FILES['fileUpload']["error"]) {
        case UPLOAD_ERR_OK:        
            break;
    }
}
    
21.01.2015 / 20:25