简体   繁体   中英

Unable implement a functionality to upload multiple images to the server

Currently, I have the following code that will allow me to upload only one image to the server at the time. But what I want to do is to upload multiple images. I don't mind if it will send multiple request to the server, but I want to replace the following code, so that I can drag and drop or select multiple images at a time and send it with ajax. How will I be able to achieve this ?

I tried to use some libraries that I found on the web such as dropzone.js, but it seems like it doesnt do the trick. Some simple samples or tips would be great ! I would love to hear from you !

HTML code

<div>
    <input type="file" name="mydata[]"/>
    <span class="btn" onclick="imgToMyServer('$(this));">Fly Me to the Server ! </span>
</div>

JS side

<script>
            function imgToMyServer(ob) {

                var form = $('<form />');
                var files = ob.prev('input[type="file"]');
                var simplefile = files.prop('files')[0];

                var Myname = simplefile.name;
                var input = $('<input name="mydata[][my_path]" value="path/' + Myname+ '"/>');
                switch (simplefile.type) {
                    case "image/jpeg":
                        break;
                    case "image/png":
                        break;
                    case "image/gif":
                        break;
                    default:');
                        return false;
                        break;
                }

                files.after(files.clone());
                files.appendTo(form);
                input.appendTo(form);
                datas = new FormData(form[0]);

                $.ajax({
                    type: 'post',
                    processData: false,
                    contentType: false,
                    data: datas,
                    url: "https//www.sample.com/uploads_my_images",
                    async: true,
                    success: function (res) {
                    //Just happy
                    }
                });
            }
        </script>

What you need its quite simple first you need to add the multiple attribute on the file input type so that it allows you to select multiple files.

Then you need to check the number of images that are selected, then loop through the array of images that are selected then append the images dynamically to the form data :

<script  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<div>
    <input type="file" name="mydata[]" id ="multiFiles" multiple="multiple">
   <button id="upload" class="btn">Fly Me to the Server !</button>

   <div id="msg"></div>
</div>

<script type="text/javascript">
            $(document).ready(function () {
                $('#upload').on('click', function (e) {
                    e.preventDefault();
                    var form_data = new FormData(); //create form data object
                    var num_files = document.getElementById('multiFiles').files.length;
                    for (var x = 0; x < num_files; x++) {
                        form_data.append("files[]", document.getElementById('multiFiles').files[x]); //append the files to the form data object
                    }
                    $.ajax({
                        url: 'upload.php', 
                        dataType: 'text', // what to expect back from the PHP script, could be json,html
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the PHP script
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the PHP script
                        }
                    });
                });
            });
        </script>

server :

<?php

if (isset($_FILES['files']) && !empty($_FILES['files'])) {
    $no_files = count($_FILES["files"]['name']);
    for ($i = 0; $i < $no_files; $i++) {
        if ($_FILES["files"]["error"][$i] > 0) {
            echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
        } else {
            if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
                echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
            } else {
                move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
                echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
            }
        }
    }
} else {
    echo 'Please choose at least one file';
}

NB: I did not do any validation of the file uploaded, I just uploaded straight, you need to validate in both the client and the server side.

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