I have an input on my website which allows the user to select a file for upload
<input type="file" name="file" id="file" />
At the end of my page, I have a button which calls a javascript function. This function needs to check if the user has specified a file for upload and if so, upload the file (php) and obtain the filename.
How can I go about accessing the file input form from javascript? i.e. how can I get the ‘post’ file information to call ‘upload_file.php’ with.
ps. I’d rather not use JQuery
edit – i’ve tried this and it doesn’t seem to work
function uploadFile(){
var files = document.getElementById('file');
var file = files.files[0];
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","uploadfile.php",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data")
var formData = new FormData();
formData.append("thefile", file);
xmlhttp.send(formData);
}
php:
<?php
echo "Upload: " . $_FILES["thefile"]["name"] . "<br />";
echo "Type: " . $_FILES["thefile"]["type"] . "<br />";
echo "Size: " . ($_FILES["thefile"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["thefile"]["tmp_name"] . "<br />";
?>
is giving me an alert saying the file name is blank, the type is blank, size is 0 etc…
Solved my problem by replacing:
with