尝试上传图像而不使用javascript刷新页面,无法正常工作

时间:2014-04-22 18:29:10

标签: javascript php jquery html xmlhttprequest

我正在尝试通过html表单将图像上传到我的服务器而不刷新页面。我的问题是文件没有上传,我无法弄清楚原因。

Javascript代码:

function uploadFiles(event) {
var fileSelect = document.getElementById('file');
var files = fileSelect.files;
var formData = new FormData();

for (var i = 0; i < files.length; i++) {
    var file = files[i];
    if (!file.type.match('image.*')) {
        alert("File: " + file.name + " is not an image and will not be uploaded.");
        continue;
    }
    formData.append('images[]', file, file.name);
}

var xhr = new XMLHttpRequest();
xhr.open('POST', '../htdocs/Php/upload_file.php', true);
xhr.onload = function () {
  if (xhr.status === 200) {
    // File(s) uploaded.
      alert('files uploaded');
  } else {
    alert('An error occurred!');
  }
};
xhr.send(formData);
}

HTML code:

<form action="../htdocs/Php/upload_file.php"  method="post" enctype="multipart/form-data">
     <input type="file" name="images[]" id="file" onchange="uploadFiles()"  multiple required />
</form>

PHP代码:

$numberOfFiles = count($_FILES['images']['name']);

for($id = 0; $id < $numberOfFiles; $id++)
{
if (!file_exists("../UploadedImages/" . $_FILES["images"]["name"][$id])) {
    move_uploaded_file($_FILES["images"]["name"][$id], "../UploadedImages/" . $_FILES["images"]["name"][$id]);
}
}

1 个答案:

答案 0 :(得分:0)

看起来您的JavaScript是正确的,但您的PHP需要一些关注。我修改了你的php,以便它首先检查是否传递了$ _FILES。然后在你的!file_exists()语句中有一些不正确的逻辑,以及如何移动和检查文件名。

要检查文件是否存在,要移动文件,您需要使用$ _FILES [&#39; images&#39;] [&#39; tmp_name&#39;]。这个名字&#39; attribute只是上传文件的名称,而不是上传到浏览器的物理文件。

要真正测试您的代码,请使用firebug并查看控制台。它应该返回一行,您可以展开并查看发布的内容和返回的内容。

这是一个例子,我给你的以下代码返回:

C:\filepath\binaries\tmp\phpDB53.tmp Was Succesuflly uploaded 
C:\filepath\binaries\tmp\phpDB54.tmp Was Succesuflly uploaded 
C:\filepath\binaries\tmp\phpDB55.tmp Was Succesuflly uploaded 
C:\filepath\binaries\tmp\phpDB56.tmp Was Succesuflly uploaded 

注意:仔细检查文件路径是否完全正确。在检查firebug控制台时,php文件也会返回文件错误,因为你有php错误报告。

//Check if files were passed through to your ajax page
if(isset($_FILES)) {

    $numberOfFiles = count($_FILES['images']['name']);

        for($id = 0; $id < $numberOfFiles; $id++)
        {
            if (file_exists($_FILES["images"]["tmp_name"][$id])) {
                move_uploaded_file($_FILES["images"]["tmp_name"][$id], $_FILES["images"]["name"][$id]);
                echo $_FILES["images"]["tmp_name"][$id] . " Was Succesuflly uploaded \r\n ";
            } else {
                echo "file didnt exists " . $_FILES["images"]["tmp_name"][$id] . "\r\n ";
            }


        }

} else {

    //No Files were passed through
    echo "no files passed through";

}

exit();

希望能回答你的问题。