使用XMLHttpRequest和FileList发布本地文件

Post local file using XMLHttpRequest and FileList

本文关键字:布本地 文件 FileList XMLHttpRequest 使用      更新时间:2023-09-26

我正试图将一个图像发送到服务器,并获取它的新名称(我移动并重命名服务器上的文件)
我可以使用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中的文件。