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
?>
6
  • What is the problem you are facing? Also the enctype attribute is used for form and not input Commented Sep 9, 2018 at 15:48
  • please check my ajax code is it sending correct data in a correct way ? Commented Sep 9, 2018 at 15:58
  • these two error are coming " Undefined index: form_data" and "Invalid argument supplied for foreach() " Commented Sep 9, 2018 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 Commented Sep 9, 2018 at 16:12
  • 1
    Possible duplicate of Upload multiple image using AJAX, PHP and jQuery Commented Sep 10, 2018 at 8:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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..
check this tutorial for more info.
can you please tell me about this $_FILES variable why it is showing the correct output and can't be upload
$_FILES is used to get HTML inputs link try $_FILES["files"] to get images
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.
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;
 }
?>  

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.