【发布时间】:2019-09-15 15:26:29
【问题描述】:
我想使用 jquery、Ajax 和 PHP 将我的数据库中的图像保存为 BLOB 文件。 我可以上传它并在表单中显示它(如果它是手动插入到数据库中的)。但是,当我在表单上更改它时,新图像会很好地显示,但是当我单击保存时,它不会保存在数据库中。我在这里没有找到任何使用 jquery、Ajax 和 PHP 的解决方案,并将整个图像存储在数据库中。
这是我的 HTML 代码(Content/users.php)的一部分:
<img src="images/defaultprofile.png" id="photoUserUpload"
name="image" onClick="triggerClick()" />
<input type="file"name="profileImage" id="profileImage" style="display:
none;" accept=".jpg, .png" onchange="displayImage(this)" />
</div>
<div>
<button id="saveTechItem" class="btn btn-primary saveTechItem">Save</button></div>
这是我的 js 代码的一部分(Data_Scripts/users.js):
$(document).on("click", ".saveItem", function() {
if (validateForm()) {
addOrUpdateItem();
}
});
function addOrUpdateItem(event) {
var itemId = $("#userId").val();
var fullName = $("#txtUserName").val();
var pic=$("#photoUserUpload").attr('src');
alert (pic);
//I tried also to append the file before submit
var file=new FormData();
file.append('file', file2);
//alert (file2);
var itemData = {
id: itemId,
postType: 'addOrUpdate',
fullName: fullName,
pic:pic
};
$.ajax({
url: 'data_ajax/users.php',
data: itemData,
type: "POST",
cache: false,
success: function(data) {
location.reload();
},
error: function(e) {
alert("error while trying to add or update user!");
}
});
}
这是我的一部分 PHP 代码(DataAjax/user.php):
if (isset($_POST['id'])) {
$postType = $_POST['postType'];
if ($postType == "addOrUpdate") {
$Id = $_POST['id'];
$FullName = $_POST['userName'];
$pic = base64_encode(file_get_contents($_POST['pic']));
$data = new Data();
$db = $data->dataHandler();
$query = "INSERT INTO Users (`id`, `fullname`, `image`)
values ('$Id', '$FullName', '$pic')";
$db->query($query);
}
}
【问题讨论】: