我的图像上传脚本的序列化表格问题

时间:2014-06-14 06:34:30

标签: javascript jquery ajax forms

我正在使用以下PHP脚本(几乎从W3Schools中复制粘贴)来存储POST表单传递的图像:

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["imageUpload"]["name"]);
$extension = end($temp);

if ((($_FILES["imageUpload"]["type"] == "image/gif")
|| ($_FILES["imageUpload"]["type"] == "image/jpeg")
|| ($_FILES["imageUpload"]["type"] == "image/jpg")
|| ($_FILES["imageUpload"]["type"] == "image/pjpeg")
|| ($_FILES["imageUpload"]["type"] == "image/x-png")
|| ($_FILES["imageUpload"]["type"] == "image/png"))
&& ($_FILES["imageUpload"]["size"] < 500000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["imageUpload"]["error"] > 0) {
    echo "Error: try again";
  } else {
    if (file_exists("upload/" . $_FILES["imageUpload"]["name"])) {
      echo "Error: a file with that name already exists";
    } else {
      move_uploaded_file($_FILES["imageUpload"]["tmp_name"],
      "upload/" . $_FILES["imageUpload"]["name"]);
      echo "upload/" . $_FILES["imageUpload"]["name"];
    }
  }
} else {
  echo "Error: make sure file is less than 500kb and is a gif/jpg/png";
}
?>

我正在使用以下jQuery将表单'ajax'发送到服务器:

// AJAX Form
$("#uploadImageForm").submit(function() {
    var url = "imageUpload.php";
    $.ajax({
        type: "POST",
        url: url,
        data: $("#uploadImageForm").serialize(), // serializes the form's elements.
        success: function(data)
        {
            alert(data); 
        }
    });
    return false;
});

如果有任何帮助,这是表单的HTML:

<div id="uploadImageDialog" title="Upload Image">
        Select the image you wish to upload.
        <form method="post" action="imageUpload.php" enctype="multipart/form-data" name="uploadImageForm" id="uploadImageForm">
            <input type="file" name="imageUpload" id="imageUpload">
            <input type="submit" value="Upload">
        </form>
</div>

当我手动提交表单时,PHP脚本正常工作。但是,当我使用AJAX提交它时,我不断收到“错误:确保文件小于500kb并且是gif / jpg / png”消息。当然,该文件确实有效,但由于某种原因,它会失败一个或多个 if 检查。我怀疑这是因为表单是序列化的。我知道序列化做了什么,但我不知道如何/如果需要在服务器脚本上接受序列化数据?或者其他地方的问题是什么?

0 个答案:

没有答案