我从输入类型文件中获取文件输入,并在onchange事件上调用一个javascript函数,如下所示:
<input type="file" onchange="readTheFile(this)">
javascript函数正在调用一个包含另一个php函数的php文件。javascrit函数是:
function readTheFile(file){
$.ajax(
{
url: 'readFile.php',
type: 'GET',
data: 'fileLoc= '+file,
success: function(output)
{
document.getElementById("content").innerHTML = output ;
}
}
);
}
</script>
我总是收到错误:
Warning: fopen( [object HTMLInputElement]) [function.fopen]: failed to open stream: No such file or directory in D:'xampp'htdocs'sha'readFile.php on line 3
Unable to open file!
readFile.php的内容是:
<?php
function readFiles($fileLoc){
$file = fopen($fileLoc, "r") or exit("Unable to open file!");
while(!feof($file)) {
echo fgets($file);
}
fclose($file);
}
if(isset($_GET['fileLoc'])){
echo readFiles($_GET['fileLoc']);
}
?>
我建议使用FILE API方法(仅限现代浏览器)
请参阅http://www.html5rocks.com/en/tutorials/file/dndfiles/
示例:
<input type="file" id="files" />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
alert(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
此处的实时示例
首先将文件移动到目录中,然后您的rest函数就会工作。
这里有一个jquery插件,可以通过ajax上传文件:jquery表单插件
这个插件将$_FILES
的参数发送到php文件中,然后首先将文件移动到目录中,然后使用fopen()
读取和显示内容。
看起来您发出的请求格式不正确。根据文档,它说数据选项直接附加到GET请求的url上。我认为这不太可能,因为您正在使用正确的php脚本。
https://api.jquery.com/jQuery.ajax/
尝试更改为
function readTheFile(file){
$.ajax(
{
url: 'readFile.php',
type: 'GET',
data: { fileLoc: file },
success: function(output)
{
document.getElementById("content").innerHTML = output ;
}
}
);
}
此外,我看不出您从$_GET数组中提取$fileLoc变量的位置。它可能只是从代码中排除。