gpt4 book ai didi

php - 包含存储为 blob 的图像的 JSON 数组

转载 作者:可可西里 更新时间:2023-11-01 09:05:37 26 4
gpt4 key购买 nike

我使用以下代码从 mySQL 表创建了一个 json 数组:

$sql = "SELECT * FROM new";

if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();

while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}

echo json_encode($resultArray);
}
function_exists('json_encode');

这仅适用于文本输入,当我尝试添加图像(存储为 BLOB)时,JSON 输出完全消失。我很清楚将图像存储在数据库中并不是一个很好的做法,但我需要以这种方式进行。谁能帮我解决这个问题?如何将图像作为 JSON 数组的一部分?

最佳答案

根据评论,这将是一个由两部分组成的答案。

1) 文件上传时,要存放到指定路径。然后应将路径和文件名存储在数据库中。以下示例未经测试,应根据您的环境进行调整:

<?php
// PHP File Upload Handler
// Store File to specific path and Insert Path and details to DB

$uploaddir = '/var/www/uploads/';
$uploadfilepath = $uploaddir . basename($_FILES['userfile']['name']);
$uploadfilename = basename($_FILES['userfile']['name'])
$uploadfiletype = $_FILES['userfile']['type'];
$uploadfilesize = $_FILES['userfile']['size'];

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfilepath)) {
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $mysqli->prepare(""INSERT INTO mediaTable (name, path, type, size) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sssi", $uploadfilename, $uploadfilepath, $uploadfiletype, $uploadfilesize);
$stmt->execute();
$stmt->close();
$mysqli->close();
$results = array(
"status" => "success",
"name" => $uploadfilename,
"type" => $uploadfiletype,
"size" => $uploadfilesize,
"path" => $uploadfilepath
);
} else {
$results = array(
"status" => "error",
"Could not save uploaded file."
);
}
?>

2) 当我们想要检索文件并通过 JSON 返回它时,它看起来像这样(同样,未经测试):

<?php
// Get Media file (POST input) from database and return data via JSON

if(isset($_POST['fn'])){
$filename = $_POST['fn'];
$results = array();
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $mysqli->prepare("SELECT name, path, type, size FROM mediaTable WHERE name=?");
$stmt->bind_param("s", $filename);
$stmt->execute();
$stmt->bind_result($fname, $fpath, $ftype, fsize);
while ($stmt->fetch()) {
$results[] = array("name" => $fname, "path" => $fpath, "type" => $ftype, "size" => $fsize, "base64" => '');
}
$stmt->close();
$mysqli->close();

foreach($results as $file){
$file['base64'] = file_get_contents($file['path']);
}
} else {
$results["error"] = "No file submitted";
}

if(isset($results)){
echo json_encode($results);
}
?>

关于php - 包含存储为 blob 的图像的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31658374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com