简体   繁体   中英

How to upload multiple images to a folder using ajax php and jquery

I am trying to upload multiple images to a folder at a time by using AJAX, JQuery, and PHP. The code is running for single file upload but not running for multiple image upload. If I am uploading a single image without loop then its working fine but in case of loop it's not working.

I am using the following code.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Upload Iamge</title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <script src="jquery-1.12.0.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#but_upload").click(function(){
                    var fd = new FormData();
                    //following  code is working fine in for single image upload
                    // var files = $('#file')[0].files[0]; 
                    // fd.append('file',files);

                    //this code not working for multiple image upload           
                    var names = [];
                    for (var i = 0; i < $('#file').get(0).files.length; ++i) {
                        names.push($('#file').get(0).files[i].name);
                    }
                    fd.append('file[]',names);

                    /*var ins = document.getElementById('file').files.length;
                    for (var x = 0; x <ins; x++) {
                        fd.append("file", document.getElementById('file').files[x]);
                    }*/

                    $.ajax({
                        url:'upload.php',
                        type:'post',
                        data:fd,
                        contentType: false,
                        processData: false,
                        success:function(response){
                            if(response != 0){
                                $("#img").attr("src",response);
                            }
                        },
                        error:function(response){
                            alert('error : ' + JSON.stringify(response));
                        }
                    });
                });
            });
        </script>
    </head>

    //HTML Part

    <body>
        <div class="container">
            <h1>AJAX File upload</h1>
            <form method="post" action=""  id="myform">
                <div>
                    <img src="" id="img" width="100" height="100">
                </div>
                <div>
                    <input type="file" id="file" name="file"  multiple="multiple" />
                    <input type="button" class="button" value="Upload" 
        id="but_upload">
                </div>
            </form>
        </div>
    </body>
</html>

//PHP Code 

<?php
    /* Getting file name */
    echo "<script>alert('yes');</script>";
    //without loop working fine
    $count = count($_FILES['file']['name']);
    for ($i = 0; $i < $count; $i++) {
        $filename = $_FILES['file']['name'][$i];
        /* Location */
        $location = "upload/".$filename;
        /* Upload file */
        if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
            echo $location;
        } else {
            echo 0;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Upload Iamge</title>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#but_upload").click(function(){
                    var fd = new FormData();
                    //following  code is working fine in for single image upload
                    // var files = $('#file')[0].files[0]; 
                    // fd.append('file',files);

                    //this code not working for multiple image upload           
                    var names = [];
                    var file_data = $('input[type="file"]')[0].files; 
                    // for multiple files
                    for(var i = 0;i<file_data.length;i++){
                        fd.append("file_"+i, file_data[i]);
                    }
                    fd.append('file[]',names);

                    /*var ins = document.getElementById('file').files.length;
                    for (var x = 0; x <ins; x++) {
                        fd.append("file", document.getElementById('file').files[x]);
                    }*/

                    $.ajax({
                        url:'upload.php',
                        type:'post',
                        data:fd,
                        contentType: false,
                        processData: false,
                        success:function(response){
                            if(response != 0){
                                $("#img").attr("src",response);
                            }
                        },
                        error:function(response){
                            alert('error : ' + JSON.stringify(response));
                        }
                    });
                });
            });
        </script>
    </head>

    //HTML Part

    <body>
        <div class="container">
            <h1>AJAX File upload</h1>
            <form method="post" action=""  id="myform">
                <div>
                    <img src="" id="img" width="100" height="100">
                </div>
                <div>
                    <input type="file" id="file" name="file"  multiple="multiple" />
                    <input type="button" class="button" value="Upload" 
        id="but_upload">
                </div>
            </form>
        </div>
    </body>
</html>

have made changes in below code

var file_data = $('input[type="file"]')[0].files; // for multiple files
    for(var i = 0;i<file_data.length;i++){
    fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);

And there are also changes in PHP code

<?php
/* Getting file name */
//without loop working fine

    $count = count($_FILES);
    for ($i = 0; $i < $count; $i++) {
        $filename = $_FILES['file_'.$i];
        /* Location */
        echo $location = "upload/".$filename['name'];
        /* Upload file */
        if(move_uploaded_file($filename['tmp_name'],$location)){
            echo $location;
        } else {
            echo 0;
    }
}
?>

count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0'] , $_FILE['file_1'] and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not , this code works for me you can try I hope it will work for you also :-)

在循环中,您需要添加特定文件的index

move_uploaded_file($_FILES['file']['tmp_name'][$i],$location); // $i is index 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM