2013-02-02 56 views
3

我正在尝试使用百分比进度进行异步文件上载。我认为这可能与FormData对象一起工作,但我不认为该帖子正在工作。我提交时没有任何反应。我已经检查过,并且没有错误,并且它没有使用JavaScript,所以PHP是好的,是否有代码有根本错误?使用XMLHttprequest上传多个文件

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"); 
    } 
} 

回答

2

你已经忘记了最重要的线在你的JavaScript代码:

request.send(data);

一压脚提升这样的:

request.setRequestHeader('Cache-Control','no-cache');

+0

我不敢相信我忘了t帽子。果然现在就起作用了。非常感谢你的看法。 – user2014429

1

request.setRequestHeader('Cache-Control','no-cache'); 

你忘了发送数据后..

request.send(data); 

顺便说一句,你需要发送正确的头

request.setRequestHeader("Content-type", ,,, 
request.setRequestHeader("Content-length",... 
request.setRequestHeader("Connection", "close"); 
+1

您实际上不想设置内容类型或长度,它们将自动处理。在Content-type的情况下,由于不会设置“边界”属性,因此执行多部分表单会实际中断。 –