2015-09-07 47 views
0

Im以下this guide使用ajax上傳圖像,主要是我可以有一個進度條。但由於某種原因,PHP腳本似乎沒有收到文件!FormData對象,似​​乎沒有上傳我的文件...

這裏是我的JavaScript:

function submitFile() { 
    var form = document.forms.namedItem("imageUpload"); 
    var formData = new FormData(form); 

    var xhr = new XMLHttpRequest(); 
    xhr.open("POST", "php/uploadImage.php", true); 
    xhr.onload = function(e) { 
     if (xhr.status == 200) { 
      console.log("uploaded!"); 
      doc("imageResponse").innerHTML = xhr.responseText; 
     } else { 
      console.log("error!"); 
      doc("imageResponse").innerHTML += "Error " + xhr.status + " occurred when trying to upload your file.<br \/>"; 
     } 
    }; 

    //Progress 
    /* 
    xhr.upload.onprogress = function(e) { 
     if (e.lengthComputable) { 
      var currentPercentage = Math.round(e.loaded/e.total * 100); 
      document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%"; 
      document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%"; 
     } 
    }; 
    */ 

    //Send data 
    xhr.send(formData); 
} 

這裏是接收文件我的PHP文件:

<?php 
session_start(); 
print_r($_FILES); 
?> 

目前該PHP文件返回一個空數組...它應該有我文件!

陣列()

回答

0

我設法解決我的代碼,這裏是同樣的問題任何人的工作版本。我決定使用JavaScript創建一個新表單並將文件字段值附加到這個新表單中。

我這樣做主要是爲了我的情況。

function submitFile(file,buttonId) { 
    //Generate a new form 
    var f = document.createElement("form"); 
    f.setAttribute("method", "POST"); 
    f.setAttribute("enctype", "multipart/form-data"); 

    //Create FormData Object 
    var formData = new FormData(f); 

    //Append file 
    formData.append("image", file.files[0], "image.jpg"); 

    var xhr = new XMLHttpRequest(); 
    xhr.open("POST", "php/uploadImage.php", true); 
    xhr.onload = function(e) { 
     if (xhr.status == 200) { 
      document.getElementById(buttonId).innerHTML = "UPLOAD COMPLETE"; 
      //console.log("uploaded!"); 
     } else { 
      //console.log("error!"); 
      alert("Error " + xhr.status + " occurred when trying to upload your file"); 
     } 
    }; 

    //Progress 
    xhr.upload.onprogress = function(e) { 
     if (e.lengthComputable) { 
      var currentPercentage = Math.round(e.loaded/e.total * 100)-1; 
      document.getElementById(buttonId).innerHTML = "UPLOAD IMAGE " + currentPercentage + "%"; 
      document.getElementById(buttonId).style.backgroundSize = (currentPercentage+1) + "% 100%"; 
      if (currentPercentage==99) { 
       document.getElementById(buttonId).innerHTML = "Processing image"; 
      } 
     } 
    }; 

    //Send data 
    xhr.send(formData); 
}