【问题标题】:Can't figure out how to upload a serializedObject and a file via AJAX不知道如何通过 AJAX 上传 serializedObject 和文件
【发布时间】:2025-12-23 10:00:07
【问题描述】:

我有一个常规的multipart/form-data,它有一些字段和 1 个fileinput。然后我通过以下方式将它发送到我的 php:

$(document).on('submit', '#create-event-form', function(){
        var form_data = JSON.stringify($(this).serializeObject());

        $.ajax({
            url: "../api/event/create.php",
            type : "POST",
            contentType : 'application/json',
            data : form_data,
            success : function(result) {
                showEvents();
            },
            error: function(xhr, resp, text) {
                // show error to console
                console.log(xhr, resp, text);
            }
        });

        return false;
    });

这反过来又被接收并保存到我的数据库中:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate event object
include_once '../objects/event.php';

$database = new Database();
$db = $database->getConnection();

$event = new Event($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

$now = new DateTime();
$timestamp = $now->getTimestamp();

$file = $_FILES['painting']['name'];
$extension = end(explode(".", $file));

$location = "painting/$timestamp" . $file . $extension;

//move_uploaded_file($_FILES['painting']['tmp_name'], $location);

// set event property values
$event->name = $data->name;
$event->max = $data->max;
$event->painting = $location;

// create the event
if($event->create()){
    $arr = array('message' => 'Evt created.');
    echo json_encode($arr);
}else{
    $arr = array('message' => 'Error creating the event.');
    echo json_encode($arr);
}

现在,如果我只通过form_data,我可以成功保存所有内容,但是,文件永远不会到达 PHP,因为我不能将php://inputmultipart/form-data 一起使用。我知道这一点,所以我正在寻找解决方法。

我尝试将文件作为 js 端的 data:{key:value} 对的一部分发送,但我无法让它工作。我已经做了几个小时了,但我不知道该怎么做(因此为什么move_uploaded_file被评论了,现在$_FILES中什么都没有,所以它失败了)。

谁能给我建议一个方法,好吗?

【问题讨论】:

    标签: php ajax file-upload


    【解决方案1】:

    HTML5 引入了 FormData 类,可用于通过 ajax 进行文件上传。 https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

    我想你会很高兴关注不同的插件。喜欢:

    并将您的逻辑与类似的工作结合起来

    我也认为这个答案可以帮助你how to do file upload using jquery serialization

    【讨论】: