【发布时间】: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://input 与multipart/form-data 一起使用。我知道这一点,所以我正在寻找解决方法。
我尝试将文件作为 js 端的 data:{key:value} 对的一部分发送,但我无法让它工作。我已经做了几个小时了,但我不知道该怎么做(因此为什么move_uploaded_file被评论了,现在$_FILES中什么都没有,所以它失败了)。
谁能给我建议一个方法,好吗?
【问题讨论】:
标签: php ajax file-upload