How to send multiple files with Ajax

Advertisements

I have Ajax Code which is sending input:file info, but i have a problem, program is sending the last file info, and I can’t get information about past files

What’s wrong? I will be grateful for help

HTML Form

        <input type="file" name="files[]" id="sss" multiple>
        <div class="bloj"></div>

PHP

    $nkar = $_FILES['file']['name'];
    $nkar_loc = $_FILES['file']['tmp_name'];
    $flr=$_FILES['file'];
    print_r($flr);
    $cc='';
    for ($i=0; $i < count($nkar); $i++) { 
        
        $location_loc="image/".$nkar[$i];
        move_uploaded_file($nkar_loc[$i],$location_loc);
        $cc.=$location_loc;


    }
    
    echo $cc;

jQuery

$('#sss').change(function (){
    // console.log(i, divmm.length)
    var fd = new FormData();
    fd.append('file[]',$(this)[0].files[0]);
        $.ajax({
        url: 'input.php',
        data: fd,
        processData: false,
        contentType: false,
        type: 'POST',
        success:function(res){
            console.log(res)
            $('.bloj').html(res)
        }
    })
})

>Solution :

This line:

fd.append('file[]',$(this)[0].files[0]);

only appends a single file. As you want to upload the multiple files from the file input, you’ll need to append them all.

for (let i = 0; i<this.files.length; ++i) { 
    fd.append("file[]", this.files[i]) 
}

Leave a ReplyCancel reply