0

我使用 PHP 成功地将图像文件存储在 MongoDB 中,当我从 Mongo db 检索图像时遇到了一些问题,谁能给出解决方案这是我的代码:

<?php
$m = new Mongo(); 
$db = $m->selectDB("example"); 
$article = $db->articles;
$files = $article->find();
$gridFS = $db->getGridFS();
?>
<table>
<?php
    $i=1;
    foreach ($files as $storedfiles) {
    ?>
    <tr>
        <td width="30%"><strong><?php echo $i; ?></strong></td>
        <td width="70%">
            <?php //echo $storedfiles["_id"]; ?>
            <?php echo "Id :".$storedfiles["_id"]; ?>
            <?php echo "Title :".$storedfiles["title"]; ?>
            <?php echo "Keywords :".$storedfiles["keywords"]; ?>

            <?php echo "Image :".$storedfiles["image"]; ?>
            <?php   $image = $gridFS->findOne(array('_id' => new MongoId($storedfiles["image"]))); 
header('Content-type: image/jpg;');
            echo $image->getBytes();
    ?>


        </td>
    </tr>
    <?php
    $i++;
    }
    ?>
    </table>
4

1 回答 1

3

您的示例没有真正意义(“文章”不是 GridFS 集合,因此其文档 _ids 可能与 GridFS 文件不匹配),但这是插入/取回图像的示例:

$m = new Mongo();
$db = $m->example;
$gridFS = $db->getGridFS();

$id = 123;

// store
$gridFS->storeFile("someFile.jpg", array("_id" => $id));

// retrieve
echo $gridFS->findOne(array("_id" => $id))->getBytes();

尝试查询$db->fs->files以查看您应该查询的 _id。

此外,您不能从任意字符串创建 MongoId。您可以使用 24 位十六进制字符串创建一个。如果您想要其他内容(如上),只需为 _id 字段使用不同的类型。

于 2012-04-06T15:04:07.103 回答