Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send multiple files with Ajax

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        <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]) 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading