Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upload multiple images using ajax in php

I am having UI like this:
enter image description here

I want to upload multiple videos using ajax in php. For that I tried FormData() in jQuery. But it's uploading only one image, not more than that.

My Form file :

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
    <button type="button" id="add"></button>
</form>

My jQuery file:

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
            var $div = $('div[id^="inputdiv"]:last');
            var num = parseInt($div.prop("id").match(/\d+/g), 10) + 1;
            var $klon = $div.clone().prop('id', 'inputdiv' + num).appendTo("#athleteRegister").insertBefore("#submitbutton");
            $('#inputdiv' + num).find("input").attr('name', 'file[' + num + ']');
            $('#inputdiv' + num).find("input").val("");
            $('#inputdiv' + num).find("input").attr('id', 'file' + num);
            $('#inputdiv' + num).find("input").css("outline", "none");
            $('#inputdiv' + num).find("div.col-sm-1 i").attr('class', 'fa fa-minus');
            $('#inputdiv' + num).find("div.col-sm-1 button").attr('id', 'remove');
            $('#inputdiv' + num).find("img").attr('alt', 'remove');
        });
        $('#sub').click(function() {
            jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
                data.append('file-' + i, file);
            });
            $.ajax({
                type: 'POST',
                data: data,
                url: "../admins/test",
                cache: false,
                contentType: false,
                processData: false,
                success: function(data) {
                    alert(data);
                }
            });
        });
    });
</script>

Can anyone solve this problem? Thanks!

like image 853
Balasuresh Asaithambi Avatar asked Oct 30 '22 08:10

Balasuresh Asaithambi


1 Answers

For ajax file upload I would recommend using dropzone.js. It has a fantastic documentation and flexibility is great.

like image 80
Nick Surmanidze Avatar answered Nov 15 '22 06:11

Nick Surmanidze