簡體   English   中英

使用XMLHttpRequest和FileList發布本地文件

[英]Post local file using XMLHttpRequest and FileList

我正在嘗試將圖像發送到服務器並重新獲得其新名稱(我在服務器上移動並重命名了文件)。
我可以使用FileList對象嗎?
我嘗試了以下代碼,但是我沒有任何錯誤,但響應為空。

HTML:

<input type="file" name="upfile" onchange="SelectImage(this);" />

JavaScript:

 function SelectImage(obj)  
    {  
    var req = new XMLHttpRequest();  
    req.open('POST', 'upload_image.php', true);  
    req.setRequestHeader('Content-type', 'multipart/form-data');  
    req.send(obj.files);  
    req.onreadystatechange = function()  
    {  
    if (req.readyState == 4 && req.status == 200)  
    console.log(req.responseText);  
    };  
   }  

PHP:

try
{
// all kind of checks to make sure the file is valid
// else throw a RuntimeException()
// then the next code:

$movedFile = sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext // derived from mime type check
);

if (!move_uploaded_file($_FILES['upfile']['tmp_name'], $movedFile))
{
throw new RuntimeException('Failed to move uploaded file.');
}

echo $movedFile;

}
catch (RuntimeException $e)
{
echo $e->getMessage();
}

您必須使用FormData對象使用xhr發送文件。 嘗試如下重寫SelectImage

function SelectImage(obj) {
  var req = new XMLHttpRequest();
  var data = new FormData();
  req.open('POST', 'upload_image.php', true);
  req.setRequestHeader('Content-type', 'multipart/form-data');
  data.append('upfile', obj.files[0]);
  req.send(data);
  req.onreadystatechange = function () {
    if (req.readyState == 4 && req.status == 200)
      console.log(req.responseText);
  };
}  

在服務器端,您將在upfile獲取該文件。

暫無
暫無

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

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