大家好,我正在尝试使用 Ajax 和 PHP 上传文件,我在教程中做了所有的事情,我得到了这个文件:upload.js:
var handleUpload = function (event){
event.preventDefault();
event.stopPropagation();
var fileInput= document.getElementById('File');
var data= new FormData();
for(var i=0;i<fileInput.files.length;i++){
data.append('file[]',fileInput.files[i]);
}
var request= new XMLHttpRequest();
request.addEventListener('progress',function(event){
if(event.lengthComputable){
alert("caesar");
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()){
progress.removeChild(progress.firstChild)
}
progress.appendChild(document.createTextNode(Math.round(percent * 100)+ ' %'));
}
});
request.upload.addEventListener('load',function(event){
document.getElementById('upload_progress').style.display='none';
});
request.upload.addEventListener('error',function(event){
alert('Upload Filed');
});
request.open('POST','upload.php');
request.setRequestHeader("Cache-Control","no-cache")
document.getElementById('upload_progress').style.display='block';
alert(request)
request.send();
}
window.addEventListener('load',function(event){
var submit = document.getElementById("Submit");
submit.addEventListener("click",handleUpload);
});
和上传.php:
<?php
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key],'./'.$name)){
$uploaded[]=$name;
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4 /strict.dtd">
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/>
<title>Upload & Ajax</title>
</head>
<script type="text/javascript" src="upload.js"></script>
<style type="text/css">
#upload_progress { display: none;}
</style>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded)){
foreach($uploaded as $name){
echo "<div><a href='./".$name."'>".$name."</a></div>";
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="File" name="file[]" multiple="multiple" />
<input type="submit" id="Submit" value="upload"/>
</div>
</form>
</div>
</body>
</html>
我刚刚点击上传,它显示 100% 我转到文件夹,如果有人可以帮助我,我找不到任何文件?