我有一个Android应用程序拍摄照片,将位图转换为Base64并将Base64字符串提交到MySQL数据库(通过PHP)存储为longblob。这部分很棒!事实上,我可以从phpMyAdmin下载longblob作为完美的Base64字符串,并轻松转换为JPEG照片。
问题是我的PHP代码获取blob返回一个空字符串:
{
"owner":"Unknown",
"pet_name":"Unknown",
"last_seen":"2019-04-09 11:17:19",
"contact":"999-888-7654",
"description":"rubber ducky, lotsa fun",
***"photo":""***,
"location":"Some location"
}
PHP getter:
function getReports() {
$stmt = $this->con->prepare("SELECT owner, pet_name, last_seen, contact, description, photo, location FROM Pets");
$stmt->execute();
$stmt->bind_result($owner, $pet_name, $last_seen, $contact, $description, $photo, $location);
$reports = array();
while($stmt->fetch()) {
$report = array();
$report['owner'] = $owner;
$report['pet_name'] = $pet_name;
$report['last_seen'] = $last_seen;
$report['contact'] = $contact;
$report['description'] = $description;
$report['photo'] = $photo;
$report['location'] = $location;
array_push($reports, $report);
}
return $reports;
}
一个有趣的旁注,如果不是上面的代码,我使用下面的代码,我得到完整的Base64字符串,但在整个过程中添加了escape()和换行符(\ n)字符:
//Select everything from table
$sql= "SELECT * FROM Pets";
//Confirm results
if($result = mysqli_query($con, $sql)) {
//Results? Create array for results and array for data
$resultArray = array();
$tempArray = array();
//Loop through results
while($row=$result->fetch_object()) {
// Add each result in results array
$tempArray=$row;
array_push($resultArray,$tempArray);
}
//Encode array to JSON and output results
echo json_encode($resultArray);
}
我想找到一种方法来修复上面的PHP代码。我想也许我的字符串太长了$photo
值?任何建议都将非常感激。
更新:从Selecting Blob from MYSQL, getting null我确实管理到Base64现在输出而不是空字符串。但是,我仍然有转义和换行符的问题。
这里有什么帮助?
我设法得到原始函数通过强制转换输出Base64行:
$stmt = $this->con->prepare("SELECT owner, pet_name, last_seen, contact, description, CAST(photo as CHAR(1000000) CHARACTER SET utf8) as photo, location FROM Pets");
虽然这允许接收Base64字符串,但它仍然包含不需要的字符。不需要的字符是由JSON_ENCODE引起的。以下是我用来解决它的问题。
基本上,1。删除添加的字符和2.告诉JSON_ENCODE不要使用JSON_UNESCAPED_SLASHES打印转义字符。
对于函数getReports()
function getReports() {
$stmt = $this->con->prepare("SELECT owner, pet_name, last_seen, contact, description, CAST(photo as CHAR(1000000) CHARACTER SET utf8) as photo, location FROM Pets");
$stmt->execute();
$stmt->bind_result($owner, $pet_name, $last_seen, $contact, $description, $photo, $location);
$reports = array();
while($stmt->fetch()) {
$report = array();
$report['owner'] = $owner;
$report['pet_name'] = $pet_name;
$report['last_seen'] = $last_seen;
$report['contact'] = $contact;
$report['description'] = $description;
$photo = str_replace("\n","",$photo);
$photo = str_replace("\\/","/", $photo);
$photo = stripcslashes($photo);
$report['photo'] = $photo;
$report['location'] = $location;
array_push($reports, $report);
}
return $reports;
}
在Api脚本中,改变了返回
echo json_encode($resultArray);
至
echo json_encode($resultArray, JSON_UNESCAPED_SLASHES);
现在一切都很棒。这是最佳做法吗?我不确定。我肯定存储base64可能不是......