jQuery FormData POST - 用于文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13750294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:56:14  来源:igfitidea点击:

jQuery FormData POST - for file upload

jqueryhtmlfile-uploadasyncfileupload

提问by Jon Rubins

I am trying to submit a full form for server side processing using jQuery. The form contains various fields including a file upload option. I am trying to use FormData to do this as I don't care about browsers that don't support it at the moment.

我正在尝试使用 jQuery 提交用于服务器端处理的完整表单。该表单包含各种字段,包括文件上传选项。我正在尝试使用 FormData 来执行此操作,因为我不关心目前不支持它的浏览器。

I have the following (simplified) jQuery code:

我有以下(简化的)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);
            }
        }
    );
});

And my server side looks like the following:

我的服务器端如下所示:

<?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);

}

?>

?>

And some relevant HTML:

以及一些相关的 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>

Right now I get an Illegal invocation error, presumably on my initialization of my FormData object. I've been searching forever of example of how to do this with jQuery and am coming up empty. Also, I want to clarify that my server side code will work. When I pass the formData as "formData" to my PHP script, how do I access the fields in it? Would it be "$_POST['formData']['field_name']" or just $_POST['field_name'] or something else entirely?

现在我收到一个非法调用错误,大概是在我的 FormData 对象初始化时。我一直在寻找如何用 jQuery 做到这一点的例子,但结果却是空的。另外,我想澄清一下我的服务器端代码可以工作。当我将 formData 作为“formData”传递给我的 PHP 脚本时,如何访问其中的字段?它是“$_POST['formData']['field_name']”还是只是 $_POST['field_name'] 或其他的东西?

Thanks for any help.

谢谢你的帮助。

回答by Musa

FormDatatakes a form element in its constructor not a jQuery object - var formData = new FormData(this);

FormData在其构造函数中采用表单元素而不是 jQuery 对象 - var formData = new FormData(this);

You have set some options for jQuery ajax to handle the formdata object so you should use $.ajax instead of $.post, also pass the formdata itself as the data.

您已经为 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);
        }
    }
});

回答by Chris McGuire

To answer your last question, I believe it would be $_POST['field_name']. Check out this post for some information on the implementation you're looking for: Sending multipart/formdata with jQuery.ajax

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

Hope this helps :)

希望这可以帮助 :)