Upload image files to mongodb gridfs in PHP

Upload image files to mongodb gridfs in PHP

Requires PHP MongoDB extension, MongoDB/MongoDB components
Install the MongoDB/MongoDB components
composer require mongodb/mongodb
//Upload the image to MongoDB Gridfs

<?php
use \MongoDB\Client;

$host = '192.168.6.1:27018,192.168.6.2:27018';
$database = 'Images';
$bucket = (new \MongoDB\Client('mongodb://'.$host.'/'.$database,
[
'username'=>'admin',
'password'=>'admin',
//'ssl' => true,
// 'replicaSet' => 'myReplicaSet',
'authSource'=>'admin',
]) )->$database->selectGridFSBucket();
$_id = new \MongoDB\BSON\ObjectId();
$metadatas=['metadata'=>['Source'=>$platform]];//metadata
$stream = $bucket->openUploadStream('my-file.jpg');
$stream = $bucket->openUploadStream('my-file.jpg',$metadatas);//with metadata
$contents = file_get_contents('/path/to/my-file.jpg');
fwrite($stream, $contents);
fclose($stream);

//download
 
header('Content-Type: image/jpg');
echo stream_get_contents($bucket->openDownloadStreamByName('my-file.jpg'));

//delete
$bucket->delete($id);


/*Get meta information (for existing files)
$ss= $bucket->openDownloadStreamByName('77777.jpg');
$metadata = $bucket->getFileDocumentForStream($ss);

//If the following file does not exist, no error will be reported
 $cursor = $bucket->find(['filename' => $ftpfilename]);
 $metadata =$cursor->toArray()[0];

var_dump($metadata);
*/

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *