2012-08-06 60 views
0

我想通过ajax发送文件到php我有下面的代码,但是当我运行它时,它说undefined索引:thefile 是什么问题? HTML通过ajax发送表单文件到php

function postData(url){ 

    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open("POST", url, true); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlHttp.onreadystatechange = function(){ 

      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { 
       var res = xmlHttp.responseText; 
       document.getElementById("upLoadName").textContent=res; 

       } 
       } 

      var formData = new FormData(); 
      formData.append("thefile", document.getElementById('thefile').files[0]); 

       xmlHttp.send(formData); 

} 

和形式:

<form action="#" > 
<input type="file" name="thefile" id="thefile"/> 
<input type="button" name="Send" value="send" onclick="postData('upLoad.php');"/> </form> 

PHP

echo json_encode($_FILES["thefile"]["name"]) ; 
+1

'$ _FILES'必须为空。我在任何地方都看不到'multipart/form-data'。 – Leri 2012-08-06 08:35:18

+0

@小巴请你解释一下吗? – user1559543 2012-08-06 09:16:39

+0

add'xmlHttp.setRequestHeader(“Content-type”,“multipart/form-data”);'onreadystatechange'前面' – Leri 2012-08-06 10:21:48

回答

0

这是你有多个文件的情况下,更应该为一个文件,以及工作:

var formData = new FormData(); 
    jQuery.each($('#thefile')[0].files, function(i, file) { 
    formData.append('thefile-'+i, file); 
}); 

的第一个文件现在可以发现:

$_FILES['thefile-0'] 

此外,一定要设置内容类型。