如何使用$ .post将图像文件从具有Ajax的输入类型文件传递到PHP

我已经看到很多关于此的主题,但是我仍然不知道如何使它与$ .post一起使用。我刚刚添加了此输入类型文件,用于将图像和文本上传到数据库。我可以在服务器端完成此操作,但不能使用Ajax。有人说使用 FormData 对象,但我仍然无法使它工作。

我的目标是使用AJAX和PHP将图像简单地移动到特定文件夹。我不知道如何通过AJAX将图像从输入类型文件传递到PHP。

我在下面提供的代码是基本代码,我可以在这里使它们易于阅读。

这是我的html

<form name="form" id="form" action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" id="message" name="message"/>
<input type="file" id="imgupload" name="file" accept="image/jpeg,image/png,image/gif"/>
<input type="submit" id="submit" name="submit" value="Submit"/>
</form>

这是我的Ajax电话

$(document).on("click","#submit",function() {
var message = $("#message").val();
var form = $("#form")[0]; //this is what I'm trying to figure out
var form_data = new FormData(form); //this is what I'm trying to figure out

$.post("upload.php",{
message: message,form_data //this is what i'm trying to pass to upload.php but doesn't work
},function(data) {
// success msg
};
});

这是我的php:

if($_FILES['file']['name'] != '') {
$filename = $_FILES['file']['tmp_name']
$path = $_FILES['file']['name'];
$fullpath = "../uploads/images/".$path;
move_uploaded_file($filename,$fullpath);

$message = $_POST['message']; //this is for the message in input text,you may ignore
$messageQuery = "insert to db...." //this is for my insert query for database,you may ignore
mysqli_query($conn,messageQuery) //again this is just a query for database,you may ignore
}
else {
echo "Failed to upload";
}
Qwea521 回答:如何使用$ .post将图像文件从具有Ajax的输入类型文件传递到PHP

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2453808.html

大家都在问