gpt4 book ai didi

php - 如何通过ajax将文件和其他数据形式作为POST对象传递到php页面并将其保存到数据库?

转载 作者:行者123 更新时间:2023-11-29 23:17:29 24 4
gpt4 key购买 nike

  • 我有一个包含文本数据的表单,我想发送表单内容和文件通过 ajax POST 方法到 Process.php 处理程序,我想获取二进制文件作为对象插入到数据库(mysql)中。
  • 我知道将文件保存到数据库中很奇怪,但在这种情况下这是必要的。
  • 还有一个问题:为什么 POST 数据以 $_POST 数组和来自 <input type="file" name="file"> 的 $_POST['file'] 发送来自同一页面未定义?

这是我的代码:PHP处理程序:(ajax将数据发送到此页面的process.php):

<?php
$mysqli = new mysqli('localhost', 'root', '', 'msgsys');
if(mysqli_connect_errno()) {
print_r("<h4 id='senterror'>Connection Failed: " . mysqli_connect_errno()."</h4>");
exit();
}
$email = $_POST['email'];
$file = $_FILES['file']['name']; //i'll try to give an object property to sure that the object exists;
$file2 = $_POST['file']; //the same attemp;
print_r($file);
if($stmt = $mysqli -> prepare("SELECT uid FROM user WHERE eaddress=?")) {
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_row($result)) {
$recUid = $row[0];
}
$stmt->close();
if (!$result || mysqli_num_rows($result) <= 0) {
print_r("<h4 id='senterror'>You Can not Mailing To Who doesn't exists!</h4>");
$mysqli->close();
exit();
} else {
date_default_timezone_set('ASIA/Tehran');
$today = date('m/d/Y-H:i:s');
$stmt = $mysqli->prepare("INSERT INTO message (sdeltag,rdeltag,rreadtag,timesent,body,subjecttxt,sender,receiver) VALUES ('0','0','0',?,?,?,'1',?)");
$stmt->bind_param("ssss",$today,$_POST['txt'], $_POST['subject'],$recUid);
$stmt->execute();
print_r("<h4 id='mailsent'>Message Sent Successfully!</h4>");
$stmt->close();
}
$mysqli->close();
}
?>

ajax:

$(document).ready(function () {
$('#sendmail').submit(function () {
var that = this;
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'proccess.php',
data: $(that).serialize()
})
.done(function (data) {
$('#response').html(data);

})
.fail(function () {
alert("Posting failed.");

});
this.reset();
return false;

});
});

最佳答案

我将重写 ajax 部分,如下所示,并且对我来说效果很好:

$(document).ready(function () {
$('#sendmail').submit(function () {
var formData = new FormData($('form')[0]);
$('#response').html("<b>Loading response...</b>");
$.ajax({
url: 'proccess.php', //Server script to process data
type: 'POST',
data: formData,
async: false,
success: function (msg) {
$('#response').html(msg);
},
cache: false,
contentType: false,
processData: false
});
this.reset();
return false;
});
});

关于php - 如何通过ajax将文件和其他数据形式作为POST对象传递到php页面并将其保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27641446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com