簡體   English   中英

如何從javascript上傳文件到服務器?

[英]How to upload a file from javascript to the server?

我正在做一個用戶需要加載照片的網頁。 由於此照片將鏈接到唯一ID,因此我希望將照片傳輸到服務器並另存為NUMBER.jpg或NUMBER.png或任何擴展名。 因此,使用javascritpt代碼調用輸入類型字段上的事件,如下所示:

   var file = document.getElementById("foto").files[0];
   document.getElementById("pathFoto").value = file.name;
   var formData = new FormData();
   formData.append('foto',file,file.name);
   var xhr = new XMLHttpRequest();
   xhr.open('POST','php/handler.php',true);
   xhr.onload = function() {
      if (xhr.status == 200){
         console.log("Done");
      }
      else{
         console.log("An error ocurred " + xhr.responseText);
      }
   }
   xhr.send(formData);

在PHP方面,這是我的工作:

$image = $_POST["foto"];
file_put_contents("atest.jpg",$image);

現在我得到的錯誤是“ foto”是未定義的索引。 誰能告訴我我在做什么錯?

這就是我要做的事情

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

initial ajax request like you did above.....


xhr.send(formData);

您始終可以從php獲取文件名。 您不必附加它。

在您的PHP中,執行

if(isset($_FILES['foto']['name])){

}

按照鏈接了解如何在php中上傳文件http://www.w3schools.com/php/php_file_upload.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM