0

I am using this following code, where user can upload one or multiple files and can delete those files. All the data is stored in form_data.

Untill now I am not able to make the file upload functionality working.

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

upload.php

<?php
//upload.php  
var_export($_FILES); // this final output that i want to upload
?>
Nitin Verma
  • 73
  • 1
  • 10
  • What is the problem you are facing? Also the enctype attribute is used for form and not input – CodeThing Sep 09 '18 at 15:48
  • please check my ajax code is it sending correct data in a correct way ? – Nitin Verma Sep 09 '18 at 15:58
  • these two error are coming " Undefined index: form_data" and "Invalid argument supplied for foreach() " – Nitin Verma Sep 09 '18 at 16:07
  • Okay. So it means this form_data is invalid in foreach($_FILES['form_data']['name']. Try printing &_FILES array in the beginning of upload file and you will get correct name – CodeThing Sep 09 '18 at 16:12
  • i just want to upload data stored in form_data but don't know how . if you can do it without ajax it also will be helpful – Nitin Verma Sep 09 '18 at 16:25
  • 1
    Possible duplicate of [Upload multiple image using AJAX, PHP and jQuery](https://stackoverflow.com/questions/28856729/upload-multiple-image-using-ajax-php-and-jquery) – Brn.Rajoriya Sep 10 '18 at 08:45

2 Answers2

4

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);
  }
});

Not same as your question but you can try like this.

Vijay Makwana
  • 911
  • 10
  • 24
  • thanku very much for your answer ,if you can see i have edit this code actually here when user delete a file from selected file the final output in $_FILES variable is correct and it shows only the file left after deleting the selected file. the output can be seen through var_export($_FILES) . i want to upload this final output but don't know how. And if the code is not correct than why the $_FILES variable is showing the correct output. please explain.. – Nitin Verma Sep 10 '18 at 07:53
  • [check](https://www.webslesson.info/2017/03/upload-multiple-files-codeigniter-ajax-jquery.html) this tutorial for more info. – Vijay Makwana Sep 10 '18 at 07:57
  • can you please tell me about this $_FILES variable why it is showing the correct output and can't be upload – Nitin Verma Sep 10 '18 at 08:02
  • $_FILES is used to get HTML inputs [link](http://www.php.net/manual/en/reserved.variables.files.php) try $_FILES["files"] to get images – Vijay Makwana Sep 10 '18 at 08:06
  • my friend if you have time please run my new edited code and then you will be able to understand what i am saying . When i var_export($_FILES) it shows the correct array that came after deleting some file . i want to upload this final output . i will suggest you to run the code in your server then you will understand what i am saying. – Nitin Verma Sep 10 '18 at 08:18
2

Here is your working code. There were several problem with your code

  1. Incorrect brace closing in ajax call.
  2. Your name field in form data was invalid
  3. You were requesting form_data as index in the $_FILES array
  4. No use of number variable

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;
 }
?>  
CodeThing
  • 2,580
  • 2
  • 12
  • 25
  • thanku very much for your answer ,if you can see i have edit this code actually here when user delete a file from selected file the final output in $_FILES variable is correct and it shows only the file left after deleting the selected file. the output can be seen through var_export($_FILES) . i want to upload this final output but don't know how. And if the code is not correct than why the $_FILES variable is showing the correct output. please explain.. – Nitin Verma Sep 10 '18 at 07:52