2012-08-06 61 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'] 

此外,一定要設置內容類型。