首页 > 解决方案 > 尝试下载 blob 时获取空值

问题描述

我在将存储在 Mysql 数据库中的图像作为 blob 下载时遇到问题。我已经尝试了很多在其他帖子中找到的解决方案,但结果每次都是一样的:

"[{"image":null},{"image":null},{"image":null}]"

我越来越多地减少我的代码以使该位置尽可能小,但什么也没有。这是我最后一次尝试,实际上是这篇文章的副本:Empty PHP output from MySQL database for a longblob

<?php
 
// Create connection
$con=mysqli_connect("Server","User","Pw","DBName");
 
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
    
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT CAST(engineerSignature as CHAR(1000000) CHARACTER SET utf8) as engineerSignature FROM tblservreport";
    
if ($result = mysqli_query($con, $sql)){
    
    $resultArray = array();
    $tempArray = array();
 
    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {       
            $tempArray = $row;
            array_push($resultArray, $tempArray);

    }
    
    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);
?>

但它也没有用。我看错地方了吗?我确定图像没问题,因为我在 Windows PC 上有另一个程序,我直接下载它而不通过 PHP,它工作正常。我阅读了很多关于为什么在这样的数据库中存储图像不是一种好方法的答案,但这不是我必须遵循的选择。

我希望其他人可以看到我所缺少的或知道我可以尝试什么。

标签: php

解决方案


在生成“JSON”之前,您必须将二进制数据编码为“base64”。

$obj = base64_encode($resultArray);
$obj_Json = json_encode($obj);
var_dump($obj_Json);

您也可以尝试此步骤来找出错误。

  1. 而不是使用echousevar_dump($resultArray)来查看该数组中发生了什么。

  2. 上传您的图片,然后转到您的 mysql 管理面板,查看文件是否已成功上传并在数据库中显示为 blob。如果不是,您在上传文件时遇到问题

  3. 确保您的 sql 查询是正确的。

而且你的问题也不清楚,所以我给了你一些基本的提示。


推荐阅读