1

I get from here : https://www.raymondcamden.com/2013/10/01/MultiFile-Uploads-and-Multiple-Selects

I try the second code

In the handleform, I change like this :

    function handleForm(e) {
        e.preventDefault();
        var data = new FormData();

        for(var i=0, len=storedFiles.length; i<len; i++) {
            data.append('files', storedFiles[i]); 
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'data_post.php', true);

        xhr.onload = function(e) {
            if(this.status == 200) {
                console.log(e.currentTarget.responseText);  
                alert(e.currentTarget.responseText + ' items uploaded.');
            }
        }

        xhr.send(data);
    }

In my data_post.php is like this : print_r($_POST);

I select some image and submit, the result is empty array like this :

Array ( )

Why the result is empty?

samuel toh
  • 6,836
  • 21
  • 71
  • 108

2 Answers2

4

This is working AJAX solution with PHP code for multiple files.
You can copy / paste whole code to your localhost or server to test.

<?php
if($_FILES) {

  if( is_array($_FILES['img']['name']) ) {
    foreach($_FILES['img']['name'] as $key => $value) {
      // upload path is the same directory as this file
      move_uploaded_file($_FILES["img"]["tmp_name"][$key], $_FILES['img']['name'][$key]);
    }
  }

//  test output
  echo "<pre>";
  print_r($_FILES);
  echo "</pre>";

  die();
}
?>


<script>
// on document ready
document.addEventListener("DOMContentLoaded", function(){

  document.getElementById("handleForm").addEventListener("click",function() {
    var formData  = new FormData( document.getElementById("form") );

    for(var i = 0; i < document.getElementById("img").files.length; i++) {
      console.log(i)
      formData.append("img[]",document.getElementById("img").files[i]);
    }

    var xhr = new XMLHttpRequest();
    // here you can change empty URL to your file
    xhr.open("POST", "");
    xhr.send(formData);
  });

});
</script>

<form action="" method="post" enctype="multipart/form-data" id="form">
  <input type="file" name="img" id="img" multiple />
  <div style="padding: 5px 10px; border: 1px solid black; cursor: pointer; display: inline-block" id="handleForm" >Send</div>
</form>
Nebojsa Nebojsa
  • 1,395
  • 1
  • 7
  • 19
1

After append file you have to post form data

var file_data = $('#sortpicture').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);
alert(form_data);                             
$.ajax({
            url: 'upload.php',  
            dataType: 'text',  
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); 
            }
 });
Waqas Ahmed
  • 185
  • 2
  • 11