使用XMLHttpRequest和FileList发布本地文件

时间:2014-09-02 09:03:57

标签: javascript php

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

1 个答案:

答案 0 :(得分:3)

您必须使用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

中的文件