[英]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.