0
votes

I am having issues with sending FormData to a PHP script, when the PHP script gets the POST it receives empty $_FILE.

HTML:

 <label class="col-md-4 control-label" for="filebutton">File Button</label>
  <div class="col-md-4">
    <input type="file" name="fileToUpload" id="fileToUpload" accept=".jpg,.jpeg.,.gif,.png,.mov,.mp4">
  </div>

JavaScript:

 const xhr = new XMLHttpRequest();

const videoForm = document.querySelector('#videoForm');
let fileToUpload = videoForm['fileToUpload'].files[0];


var formdata = new FormData();
formdata.append("fileToUpload", fileToUpload);

xhr.onload = function () {
  let serverResponse = this.responseText;
  console.log(serverResponse);

  if(serverResponse === "SUCCESS"){
    //GatherDBData();
  }else{
    alert("Error file was NOT uploaded, check file type");
  }

};


xhr.open("POST", "upload.php");
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formdata);

PHP:

if($_POST){
  if($_FILES["fileToUpload"]["name"] != '')
  {
    $test = explode('.', $_FILES["fileToUpload"]["name"]);
    $ext = end($test);
    $name = $_FILES["fileToUpload"]["name"];
    $location = '../../VideoDropPoint/' . $name;
    if (file_exists($location)) {}
    if(move_uploaded_file($_FILES["fileToUpload"]["name"], $location)){
      echo "SUCCESS";
    }else{
      echo "ERROR";
    }
    echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
  }else{
    echo "ERROR no data received";
  }
}

PHP gets past the if($_POST), but finds the if($_FILES["fileToUpload"]["name"] != '') false.

1
The Content-Type header needs to contain the used boundary value as well for multipart requests, but you are sending one that doesn’t. Try and remove that line completely, AFAIK browsers handle this on their own internally based on the combination of XMLHttpRequest and FormData being used.CBroe
Nope still not working, commented out the setRequestHeader.Tian Openlab
Not sure if this is supposed to work fully by itself, if you just try to serialize the file input field on its own. Try the approach here, where simply the whole form gets serialized via FormData, developer.mozilla.org/en-US/docs/Web/API/FormData/… - and make sure your form has the proper enctype set.CBroe
It's Still empty.Tian Openlab

1 Answers

0
votes

change your JS code like below:

<script>
    document.querySelector('#fileToUpload').addEventListener('change', function(e) {
      var file = this.files[0];

      var fd = new FormData();
      fd.append("fileToUpload", file);
      fd.append("param", "test");

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

      xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
          var percentComplete = (e.loaded / e.total) * 100;
          console.log(percentComplete + '% uploaded');
        }
      };

      xhr.onload = function() {
        if (this.status == 200) {
          var resp = JSON.parse(this.response);

          console.log('Server got:', resp);

          var image = document.createElement('img');
          image.src = resp.dataUrl;
          document.body.appendChild(image);
        };
      };

      xhr.send(fd);
    }, false);
    </script>

and in PHP I have fixed move_uploaded_file and some if condition as well

if($_POST){
  if($_FILES["fileToUpload"]["name"] != '')
  {
    $test = explode('.', $_FILES["fileToUpload"]["name"]);
    $ext = end($test);
    $name = $_FILES["fileToUpload"]["name"];
    $location =  '../../VideoDropPoint/';
    if (file_exists($location)) {
        print_r($_FILES["fileToUpload"]);
        if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $location.$name)){
          echo "SUCCESS";
        }else{
          echo "ERROR";
      } 
    }
    echo '<img src="'.$location.$name.'" height="150" width="225" class="img-thumbnail" />';
  }else{
    echo "ERROR no data received";
  }
}