We are going to make some changes in our earlier example. When serving an image file from GridFS to the browser, we are going to read the image in chunks, instead of loading the entire file in memory. Let's see how we can do that:
1. Create a new PHP file in your text editor and add the following lines of code to it:
<?php $id = $_GET['id']; require 'dbconnection.php'; $mongo = DBConnection::instantiate(); $gridFS = $mongo->database->getGridFS(); $object = $gridFS->findOne(array('_id' => new MongoId($id))); //find the chunks for this file $chunks = $mongo->database->fs->chunks->find(array('files_id' => $object->file['_id'])) ->sort(array('n' => 1)); header('Content-type: '.$object->file['filetype']); //output the data in chunks foreach($chunks as $chunk){ echo $chunk['data']->bin; }
2. Save the file as
stream.php
.3. Open the
list.php
file. Find the following line in it:<a href="image.php?id=<?php...