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

时间:2015-07-27 16:24:12

标签: php mysql json

我使用以下代码从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 个答案:

答案 0 :(得分:0)

根据评论,这将是一个2部分答案。

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);
}
?>