通过XMLHttpRequest传递纯文本文件失败
问题描述:
I am trying to send a user uploaded text file via an XMLHttpRequest with the following code:
HTML
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
Javascript
function Upload_Text()
{
var file = document.getElementById("file").files[0];
var table_type = 2;
if (document.myform.Table_Name_Text[0].checked == true) {table_type = 1;}
var Choose_Class = document.getElementById("Choose_Class").value;
var formData = new FormData();
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
alert(result);
}
}
var url = "Upload_Text.php";
url = url + "?table_type="+table_type;
url = url + "&Choose_Class="+Choose_Class;
formData.append("thefile", file);
xmlhttp.open('POST', url, true);
xmlhttp.send(formData);
}
However with the following PHP code, I do not receive any data from the text file server side.
<?php
$file = $_FILES['thefile'];
$table_type=$_REQUEST["table_type"];
$Choose_Class=$_REQUEST["Choose_Class"];
$fh = fopen($file, 'r');
$theData = fread($fh, filesize($file));
fclose($fh);
echo $theData;
?>
Any help with this would be great, thanks.
答
Try adding ["tmp_name"] to the file string. So: $file = $_FILES['thefile']['tmp_name'];
This will get the file's temporary location. Looking through your code everything else seems fine.