【发布时间】:2017-04-01 21:02:57
【问题描述】:
您好,我正在尝试使用 php ajax 和 html 将添加了 cmets 的图像上传到数据库中。
这里是html部分:
<form name="form1" enctype="multipart/form-data" action="">
<h2></h2>
<div class="form-group">
<textarea name="msg" class="form-control status-box" id="post" rows="3" cols="60" placeholder="What\'s on your mind?"></textarea>
<p>Upload an image.</p>
<input type="file" id="postPhoto" name="postPhoto" value="upload" placeholder="Upload Image">
</div>
</form>
<div class="button-group pull-right">
<p class="counter">200</p>
<a href="#" type="submit" onclick="submitChat()" class="post btn btn-primary">
Post</a>
</div><br><br>
这就是我对 ajax 的要求,它与 html 位于同一页面上
<script>
function submitChat() {
var file = document.getElementById("postPhoto");
var formData = new FormData();
// alert(formData);
formData.append("file[]", file.files[0]);
if(form1.msg.value == '') {
alert('You must Enter a Post');
return;
}
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById('logs').innerHTML = xmlhttp.responseText;
console.log(xmlhttp.statusText);
}
}
xmlhttp.open('POST', 'userposts.php?msg='+msg, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send(formData);
}
<script>
这是php部分:
$msg = stripslashes(htmlspecialchars($_REQUEST['msg']));
if(isset($_FILES['postPhoto']['type'])) {
$imageData = "";
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES['postPhoto']['name']);
$file_extension = end($temporary);
if((($_FILES['postPhoto']['type'] === 'image/png') || ($_FILES['postPhoto']['type'] == 'image/jpg') || ($_FILES['postPhoto']['type'] == 'image/jpeg')) && ($_FILES['postPhoto']['size'] < 2500000) && in_array($file_extension, $validextensions)) {
if($FILES['postPhoto']['error'] > 0) {
echo "return code: " . $_FILES['postPhoto']['error'] . "<br/><br/>";
}
else {
$imageData = mysqli_real_escape_string($connection, file_get_contents($_FILES["postPhoto"]["tmp_name"]));
}
}
}
$stmt = "INSERT INTO posts VALUES ('', '$uname', '$msg', '$imageData')";
$result = $connection->query($stmt);
图像似乎没有被发送到 php 文件 idk 如何解决这个问题。任何帮助将不胜感激。
【问题讨论】:
-
试试
$_FILES['postPhoto']而不是$_FILES['file'] -
试试我的解决方案,我已经在另一个帖子上回答了,看看这个->stackoverflow.com/questions/40582426/…
-
@AmitChauhan 我认为 OP 不想使用 jQuery
-
可能他得用ajax,很简单
-
嘿,你有答案吗?如果有,请提供给我们,谢谢,,[等待的家伙]
标签: javascript php html ajax image-processing