如何使用ajax在php中上传多张图片

5

我有一个UI长这样:
enter image description here

我想要使用ajax在php中上传多个视频。为此,我尝试了jQuery中的FormData()。但它只能上传一个图像,而不能上传多个。

我的表单文件:

<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>

我的jQuery文件:

<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>

有人能解决这个问题吗? 谢谢!


1
请使用serializeArray()将输入发送到服务器端。或者您可以使用任何第三方插件,例如https://blueimp.github.io/jQuery-File-Upload/。 - Nisam
@Nisam 我需要仅使用上述代码来执行。 - Balasuresh Asaithambi
3个回答

1

对于ajax文件上传,我建议使用dropzone.js。它有极好的文档和很大的灵活性。


1

0

你可以轻松地通过this插件实现这一点。

<form method="post" action="server/form_process.php">
   <!-- This area will show the uploaded files -->
   <div class="row">
      <div id="uploaded_images">
      </div>
   </div>
   <br>
   <br>
   <div id="select_file">
      <div class="form-group">
         <label>Upload Image</label>
      </div>
      <div class="form-group">
         <!-- The fileinput-button span is used to style the file input field as button -->
         <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Select file...</span>
            <!-- The file input field used as target for the file upload widget -->
            <input id="fileupload" type="file" name="files" accept="image/x-png, image/gif, image/jpeg" >
         </span>
         <br>
         <br>
         <!-- The global progress bar -->
         <div id="progress" class="progress">
            <div class="progress-bar progress-bar-success"></div>
         </div>
         <!-- The container for the uploaded files -->
         <div id="files" class="files"></div>
         <input type="text" name="uploaded_file_name" id="uploaded_file_name" hidden>
         <br>
      </div>
   </div>
   <button type="submit" class="btn btn-primary" name="submit">Submit</button>
</form>

然后添加这个脚本!

<script>
    /*jslint unparam: true */
    /*global window, $ */

    var max_uploads = 5

    $(function () {
        'use strict';

        // Change this to the location of your server-side upload handler:
        var url = 'server/upload.php';
        $('#fileupload').fileupload({
            url: url,
            dataType: 'html',
            done: function (e, data) {

                if(data['result'] == 'FAILED'){
                    alert('Invalid File');
                }else{
                    $('#uploaded_file_name').val(data['result']);
                    $('#uploaded_images').append('<div class="uploaded_image"> <input type="text" value="'+data['result']+'" name="uploaded_image_name[]" id="uploaded_image_name" hidden> <img src="server/uploads/'+data['result']+'" /> <a href="#" class="img_rmv btn btn-danger"><i class="fa fa-times-circle" style="font-size:48px;color:red"></i></a> </div>');

                    if($('.uploaded_image').length >= max_uploads){
                        $('#select_file').hide();
                    }else{
                        $('#select_file').show();
                    }
                }

                $('#progress .progress-bar').css(
                    'width',
                    0 + '%'
                );

                $.each(data.result.files, function (index, file) {
                    $('<p/>').text(file.name).appendTo('#files');
                });

            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    });

    $( "#uploaded_images" ).on( "click", ".img_rmv", function() {
        $(this).parent().remove();
        if($('.uploaded_image').length >= max_uploads){
            $('#select_file').hide();
        }else{
            $('#select_file').show();
        }
    });
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接