用PHP把 图片,文件上传到 mongodb gridfs 中

需要 php mongodb扩展, mongodb/mongodb 组件
安装 mongodb/mongodb 组件
composer require mongodb/mongodb
//把图片上传到 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();
 
$stream = $bucket->openUploadStream('my-file.jpg');
$contents = file_get_contents('/path/to/my-file.jpg');
fwrite($stream, $contents);
fclose($stream);

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


/*取得元信息(针对已存在文件)
$ss= $bucket->openDownloadStreamByName('77777.jpg');
$metadata = $bucket->getFileDocumentForStream($ss);

//用以下文件不存在时不会报错
 $cursor = $bucket->find(['filename' => $ftpfilename]);
 $metadata =$cursor->toArray()[0];

var_dump($metadata);
*/

 

原创文章,转裁请注明:来自Lenix的博客,地址 http://blog.p2hp.com/archives/5329

用PHP把 图片,文件上传到 mongodb gridfs 中
标签:         

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*