我正在尝试创建一个异步文件上载表单,其中包含百分比进度。我认为这可能适用于FormData对象,但我认为帖子不起作用。当我提交时没有任何反应。我已经检查过并且没有错误,并且它可以在没有javascript的情况下运行,所以PHP可以在代码中出现根本错误吗?
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.upload.addEventListener('progress',function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNones()){
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("failed");
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
};
window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});
html:
<div id = "upload_progress"></div>
<form id="form" action="" method="post" enctype="multipart/form-data">
<input id="file" name="file[]" type="file" multiple /><br>
<input type="submit" name="send" id ="submit" value="send">
</form>
和upload.php
if(!empty($_FILES['file'])){
foreach ($_FILES['file']['name'] as $key => $name) {
move_uploaded_file($_FILES['file']['tmp_name'][$key],"myfiles/$name");
}
}
答案 0 :(得分:2)
您忘记了javascript代码中最重要的一行:
request.send(data);
之后:
request.setRequestHeader('Cache-Control','no-cache');
答案 1 :(得分:1)
之后
request.setRequestHeader('Cache-Control','no-cache');
您忘了发送数据..
request.send(data);
顺便说一句,您需要发送正确的标题
request.setRequestHeader("Content-type", ,,,
request.setRequestHeader("Content-length",...
request.setRequestHeader("Connection", "close");