I successfully stored image files in MongoDB using PHP, when i retrieve images from Mongo db i had some problem, can anyone give the solution Here is my code:
<?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>
Your example doesn't really make sense ("articles" isn't a GridFS collection, so its documents _ids probably wouldn't match GridFS files), but here's an example of inserting/getting back an image:
$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();
Try querying $db->fs->files
to see what _ids you should be querying for.
Also, you can't create a MongoId from an arbitrary string. You can create one with a 24-digit hexidecimal string. Just use a different type for the _id field if you want something else (as above).