【发布时间】:2019-07-31 00:01:38
【问题描述】:
我正在尝试使用 AJAX 和 PHP 将图像上传到数据库。当我单击表单的提交按钮时,ajax 应该将图像的信息发送到一个 php 页面,它将被插入到数据库中。这是图片上传的表格:
<form enctype='multipart/form-data' class='img-form'>
<input type='hidden' name='size' value='1000000'>
<input type='file' name='image' id='file-input' class='profile-file'>
<input type='submit' name='upload' value='Upload Image' id='submit-input'>
</form>
然后,当我点击表单的提交按钮/输入类型时,我通过调用我将请求放入的函数来发送 ajax 请求:
$(".img-form-container").on("click", "#submit-input", function(e) {
e.preventDefault();
setImage();
}
这是setImage() 函数:
function setImage() {
var sessid = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/profile/set_image.php',
type: 'POST',
data: {sessid: sessid},
success: function(data) {
console.log("successful image update");
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
}
最后,在一个单独的文件中,我有接收 AJAX 请求的 PHP 代码:
$allowed = ['image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'];
if (in_array($_FILES['image']['type'], $allowed)) {
$sessid= $_REQUEST['sessid'];
$target = "images/".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];
$q = "INSERT INTO profileimages (image, idUsers) VALUES ('$image', '$sessid')";
$r = mysqli_query($conn, $q);
} else {
echo "<p class='errormsg'>Only JPG and PNG files are permitted.</p>";
}
问题是我需要$target 和$image 变量所需的信息,但我不知道如何从javascript 中获取。
我已经尝试将一些 PHP 代码添加到 JS 函数 setImage() 以发送到 PHP 文件,如下所示:
function setImage() {
<?php
if (isset($_POST['upload'])) {
$target = "images/".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];
}
?>
var target = "<?php echo $target ?>";
var image = "<?php echo $image?>";
var sessid = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/profile/set_image.php',
type: 'POST',
data: {sessid: sessid, image: image, target: target},
success: function(data) {
console.log("successful image update");
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
});
}
但它给了我这个错误:
<b>Notice</b>: Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>127</b><br />
<br />
<b>Notice</b>: Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>128</b><br />
基本上,我需要从$target 和$image 变量($_FILES['image'] 等)中获取信息到一个javascript 变量中。有没有办法我可以做到这一点?
这个系统最初在我使用纯 PHP 构建我的网站时工作,但由于我添加了 AJAX,我无法编辑代码以使其工作。
让我知道是否有助于添加更多代码,或者我在发布代码时是否犯了错误。
【问题讨论】:
-
先检查有没有数据。试试 echo $_FILES['image']['name'];在你的 setImage 函数的开始,看看你得到了什么信息。
-
逻辑是倒退的。在上传之前不会在 php 中看到文件。需要使用 FormData API 进行上传。见stackoverflow.com/questions/166221/…
-
@Icewine 我试过了,它给了我这个错误:
通知:未定义索引:C:\xampp\htdocs\Real 网站中的图像\profile.php 在 176
行 -
@charlietfl 我会调查一下