如何通过Ajax jQuery上传多个图像

时间:2018-09-09 15:06:37

标签: php jquery html ajax

我正在使用以下代码,用户可以在其中上传一个或多个文件,并可以删除这些文件。所有数据都存储在$.contextMenu中。

到目前为止,我无法使文件上传功能正常工作。

index.php

form_data

upload.php

<input id="avatar" type="file" name="avatar[]" multiple />
<button id="upload" value="Upload" type="button">upload</button> 

<div class="preview">
</div>

<div class="return_php"></div>

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
    $(document).ready(function () {
        var form_data = new FormData();
        var number = 0;

        /* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
        $(document).on('change', '#avatar', function () {
            console.log($("#avatar").prop("files").length);
            len_files = $("#avatar").prop("files").length;
            for (var i = 0; i < len_files; i++) {
                var file_data = $("#avatar").prop("files")[i];
                form_data.append(file_data.name, file_data);
                number++;
                var construc = '<img width="200px" height="200px" src="' +
                    window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
                $('.preview').append(construc);
            }
        });

        /* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
        $(document).on('click', 'img', function () {

            var filename = $(this).attr('alt');
            var newfilename = filename.replace(/\./gi, "_");
            form_data.delete($(this).attr('alt'))
            $(this).remove()

        });

        /* UPLOAD CLICK */
        $(document).on("click", "#upload", function () {
            $.ajax({
                url: "upload.php",
                dataType: 'script',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data, // Setting the data attribute of ajax with form_data
                type: 'post',
                success: function (data) {
                    $('.return_php').html(data);
                }
            })
        })
    });
</script>

2 个答案:

答案 0 :(得分:2)

HTML

<div class="col-md-6" align="right">
    <label>Select Multiple Files</label>
</div>
<div class="col-md-6">
    <input type="file" name="files" id="files" multiple />
</div>
<div style="clear:both"></div>
<br />
<br />
<div id="uploaded_images"></div>

JavaScript

$('#files').change(function(){
   var files = $('#files')[0].files;
   var error = '';
   var form_data = new FormData();

   for(var count = 0; count<files.length; count++)
   {
      var name = files[count].name;
      var extension = name.split('.').pop().toLowerCase();

      if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
      {
          error += "Invalid " + count + " Image File"
      }
      else
     {
        form_data.append("files[]", files[count]);
     }
   }
   if(error == '')
   {
       $.ajax({
          url:"url",
          method:"POST",
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function()
         {
             $('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
         },
         success:function(data)
         {
             $('#uploaded_images').html(data);
             $('#files').val('');
         }
     })
  }
  else
  {
      alert(error);
  }
});

与您的问题不同,但是您可以这样尝试。

答案 1 :(得分:0)

这是您的工作代码。 您的代码有几个问题

  1. 在ajax调用中括号关闭不正确。
  2. 您在表单数据中的姓名字段无效
  3. 您正在请求form_data作为$ _FILES数组中的索引
  4. 不使用数字变量

index.php

<input id="avatar" type="file" name="avatar[]" multiple="multiple" 
    />
 <button id="upload" value="Upload" type="button">upload</button> 

<div class="preview">
</div>

<div class="return_php"></div>

<script   src="https://code.jquery.com/jquery-3.1.0.min.js" ></script>
    <script>
    $(document).ready(function(){
        var form_data = new FormData(); 

        /* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
        $(document).on('change','#avatar',function(){
            $('.preview').html("");
            len_files = $("#avatar").prop("files").length;
            for (var i = 0; i < len_files; i++) {
                var file_data = $("#avatar").prop("files")[i];
                form_data.append("avatar[]", file_data);
                var construc = '<img width="200px" height="200px" src="' +  window.URL.createObjectURL(file_data) + '" alt="'  +  file_data.name  + '" />';
                $('.preview').append(construc); 
            }
        }); 

        /* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
        $(document).on('click','img',function(){
            var filename = $(this).attr('alt');
            var newfilename = filename.replace(/\./gi, "_");
            form_data.delete($(this).attr('alt'));
            $(this).remove();
        });

        /* UPLOAD CLICK */
        $(document).on("click", "#upload", function() {
            $.ajax({
                url: "upload.php",
                dataType: 'image/png',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data, // Setting the data attribute of ajax with form_data
                type: 'post',
                success: function(data) {
                    //console.log("data")'  
                }
            });
        });
    });
</script>

upload.php

<?php
 //upload.php  
 $output = '';  
 if(is_array($_FILES) && !empty($_FILES['avatar']))  
 {  
      foreach($_FILES['avatar']['name'] as $key => $filename)  
     {  
          $file_name = explode(".", $filename);  
           $allowed_extension = array("jpg", "jpeg", "png", "gif");  
           if(in_array($file_name[1], $allowed_extension))  
           {  
                $new_name = rand() . '.'. $file_name[1];  
                $sourcePath = $_FILES["avatar"]["tmp_name"][$key];  
                $targetPath = "uploads/".$new_name;  
                move_uploaded_file($sourcePath, $targetPath);  
           } 
      }  
     $images = glob("uploads/*.*");  
      foreach($images as $image)  
     {  
           $output .= '<div class="col-md-1" align="center" ><img src="' .  $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';  
      }  
      echo $output;
 }
?>