[英]uploading files using ajax and php
嗨,大家好,我正在尝试使用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);
});
和upload.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%我转到了文件夹,并且找不到任何文件可以帮助我吗?
首先检查您的PHP文件是否在没有精美JS的情况下工作。 通过表单POST进行常规文件上传。 上载的文件将转到当前文件夹,即'./'.$name
。 将文件夹更改为您希望文件上传到的文件夹。
HTML / PHP完美无瑕后,请立即修复JS。
在上传文件时,应始终注意以下事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.