jQuery FormData POST - 用于文件上传

5
我将尝试使用jQuery提交包含文件上传选项的完整表单以供服务器端处理。我将使用FormData来实现此操作,因为目前我不关心不支持它的浏览器。
以下是(简化的)jQuery代码:
$("#create_event_form").submit(function(event) {
    event.preventDefault();

    var formData = new FormData($(this));

    $.post(
        "create_entity.php",
        { formData: formData },
        function(data) {
            var response = jQuery.parseJSON(data);
            if(response.code == "success") {
                alert("Success!");
            } else if(response.code == "failure") {
                alert(response.err);
            }
        }
    );
});

我的服务器端代码如下:

<?php
require_once('includes/database.php');


$dbh = db_connect();

$response = array();
if($_SERVER['REQUEST_METHOD'] == "POST") {
    // do some other stuff...       

    // upload entity picture and update database
    $url = $_FILES['entity_pic']['name'];
    if($url != "") {
        if($type == "user") {
            $pic_loc = "images/profiles/";
        } else if($type == "chapter") {
            $pic_loc = "images/chapters/";
        } else if($type == "group") {
            $pic_loc = "images/groups/";
        } else if($type == "event") {
            $pic_loc = "images/events/";
        }
        // upload the picture if it's not already uploaded
        if(!file_exists($pic_loc . $_FILES['entity_pic']['name'])) {
            move_uploaded_file($_FILES['entity_pic']['tmp_name'], $pic_loc . $url);
        }
        $image_query = "INSERT INTO image (entity_id, url, type) VALUES (:entity_id, :url, :type);";
        $image_query_stmt = $dbh->prepare($image_query);
        $image_query_stmt->bindParam(":entity_id", $entity_id);
        $image_query_stmt->bindParam(":url", $url);
        $image_query_stmt->bindValue(":type", $type);
        if(!$image_query_stmt->execute()) {
            die(print_r($image_query_stmt->errorInfo()));
        }
    }


    echo json_encode($response);

}

?>

还有一些相关的HTML:

<form id="create_event_form" action="create_entity.php" method="POST" enctype='multipart/form-data'>
    <input type="file" name="entity_pic" value="Insert Photo" />
    <!-- other inputs -->
</form>

现在我遇到了非法调用错误,这可能是因为我初始化了我的FormData对象。我一直在寻找使用jQuery完成此操作的示例,但一无所获。此外,我想澄清的是,我的服务器端代码将会起作用。当我将formData作为“formData”传递给我的PHP脚本时,我该如何访问其中的字段?是“$_POST['formData']['field_name']”,还是只有“$_POST ['field_name']”,或者完全不同的内容?

谢谢您的任何帮助。


类似于这个stackoverflow问题的吗? - Toni Toni Chopper
唯一的问题是,在我要提交的表单中,还有大量其他值。我是否需要为每个值都执行一个追加语句?我本来希望能够使用表单引用初始化FormData对象... - Jon Rubins
另外,我需要帮助理解如何在服务器端代码中处理提交的FormData对象。 - Jon Rubins
2个回答

15

FormData的构造函数需要一个表单元素作为参数而不是jQuery对象 - var formData = new FormData(this);

您已经为jQuery ajax设置了一些选项来处理formdata对象,因此应该使用$.ajax而不是$.post,同时将formdata本身作为数据传递。

$.ajax({
  url: "create_entity.php",
  data: formData,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data) {
        var response = jQuery.parseJSON(data);
        if(response.code == "success") {
            alert("Success!");
        } else if(response.code == "failure") {
            alert(response.err);
        }
    }
});

1

回答你的最后一个问题,我相信应该是 $_POST['field_name']。查看这篇文章,了解一些你正在寻找的实现信息: 使用jQuery.ajax发送multipart/formdata

希望这可以帮到你 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接