Im using XMLHttpRequest to upload a file to a php script. The problem is i cant change the file name from the client side and im struggling to work out how to send a variable with the file.
I have a textbox on the screen and basically when the user submits the file, i want the text from the textbox to go to the php file aswel.
Here is my upload function:
function uploadFile() {
var fd = new FormData();
var count = document.getElementById('fileToUpload').files.length;
for (var index = 0; index < count; index ++)
{
var file = document.getElementById('fileToUpload').files[index];
fd.append('myFile', file);
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "savetofile.php");
xhr.send(fd);
}
and in the php file :
<?php
if (isset($_FILES['myFile'])) {
// $text = contents of the textbox that has been sent from javascript
move_uploaded_file($_FILES['myFile']['tmp_name'], "daa_coke/images/" . $_FILES['myFile']['name']);
$xml = simplexml_load_file('daa_coke/newcoke.xml');
$employee = $xml->addChild('flight');
$employee->addChild('to', 'dsd');
$employee->addChild('from', 'Gary');
$employee->addChild('imagepath', $_FILES['myFile']['name']);
$employee->addChild('templateStyle', 'template1');
$employee->addChild('time', '13:37');
$employee->addChild('date', '24/12/16');
file_put_contents('daa_coke/newcoke.xml', $xml->asXML());
}
?>
I just want to be able to pass the contents of the textbox so i canput it in the $test variable.
The filename
should be third parameter passed to .append()
formData.append(name, value, filename);
e.g.;
fd.append("myFile", file, this.querySelector("input[type=text]").value);