【发布时间】:2014-12-24 19:30:37
【问题描述】:
- 我有一个包含文本数据的表单,我想发送一个表单内容和文件 通过 ajax POST 方法到 Proccess.php 处理程序,我想得到 二进制文件作为对象插入到数据库(mysql)中。
- 我知道将文件保存到数据库很奇怪,但在这种情况下是必要的。
- 还有一个问题:为什么 POST 数据在 $_POST 数组中发送,而来自同一页面的
<input type="file" name="file">的 $_POST['file'] 未定义?
这是我的代码: PHP handler:(proccess.php 哪个ajax 向这个页面发送数据):
<?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;
});
});
【问题讨论】:
-
@Musa 只保留文件,表单数据的其他字段呢?
-
当您发布文件时,您不会使用 $_POST['file'] 访问它,它会存储在文件的服务器全局变量中:$_FILES['file']
-
@ARH 你读过这个答案了吗stackoverflow.com/a/8758614/1353011
-
@Colum $_FILES['file'] 它说它是未定义的,但我认为所有的表单内容,包含文件,用 ajax 发布到 proccess.php,不是吗?
标签: php jquery mysql ajax asyncfileupload