File Upload Multiple via ajax - PHP

Asked

Viewed 1,104 times

5

I am trying to upload files via ajax and PHP with the following codes below and it is not working. I can’t 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 Modeloc js Ajax upload.php on line 3

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

Worked

Thank you very much for your personal help

  • What exactly isn’t working? Gives some error?

2 answers

3

The first warning is why you have not checked whether fileUpload was a 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 this case you should use switch.

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

2


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

See how you can do:

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 type of error in PHP you should always check if the index really 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 to your PHP code to make sure that the files were actually uploaded and no errors occurred in the process.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.