0

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>
Community
  • 1
  • 1
senthilbp
  • 807
  • 1
  • 9
  • 16
  • What are you trying to do? example.articles isn't a GridFS collection, does the _id of docs in that collection match the _id of your GridFS files? – kris Mar 29 '12 at 14:12
  • I have confused about images retrieval, i got _id from collection , By using that _id i can't get image ,I had error in header('Content-type: image/jpg;'); echo $image->getBytes();, provide me the solution and also for multiple file upload & retriveal show using MongoDB with PHP , thanks – senthilbp Mar 30 '12 at 05:00

1 Answers1

3

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).

kris
  • 23,024
  • 10
  • 70
  • 79