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