我的mysql数据库中有一个图像,类型为longblob。我有一个请求图像和成功的ajax调用,将我的html图像src更改为接收到的图像。我的ajax post响应是图像名称(114046.png),但它会触发ajax错误部分,而不是成功。有人可以查看我的代码并告诉我哪里出错了吗?
在DB中保存图像
public function UploadImage($imageData) {
global $dbCon;
$imgFile = $imageData['file']['name'];
$imgSize = $imageData['file']['size'];
if(empty($imgFile)){
error_log("image file empty");
}
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
if(!in_array($imgExt, $valid_extensions)) {
error_log("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
}
// Check file size '5MB'
if($imgSize > 5000000) {
error_log("Sorry, your file is too large.");
}
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
$sql = 'UPDATE userinfo SET image=(:image) WHERE username="'.$this->currentUsername.'"';
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':image', $userpic);
$stmt->execute();
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
//image uploaded
}
}
从数据库中获取图像
public function GetImage() {
global $dbCon;
$stmt = $dbCon->query("SELECT image FROM userinfo WHERE username='".$this->currentUsername."'");
$fetchResult = $stmt->fetch();
$data = $fetchResult["image"];
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
$this->LatestUpdate = "Get Image";
$this->image = $data;
}
}
public function GetTheImage() {
return $this->image;
}
回应ajax
if($this->model->LatestUpdate() == "Get Image") {
header("Content-type: image/png");
echo $this->model->GetTheImage();
exit();
}
Ajax调用(将HTML图像设置为接收的图像)
window.onload = SetImage;
function SetImage() {
data = "action=" + "getImage";
$.ajax({
url: '../index.php', // point to server-side PHP script
dataType: 'image/png', // what to expect back from the PHP script, if anything
data: data,
type: 'post',
success: function(image) {
console.log("success");
$("#profileImage").attr("src", image);
}, error: function(xhr, status, error) {
alert("Error" + xhr.responseText);
}
});
}