需要 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();
$metadatas=['metadata'=>['Source'=>$platform]];//metadata
$stream = $bucket->openUploadStream('my-file.jpg');
或 $stream = $bucket->openUploadStream('my-file.jpg',$metadatas);//带metadata
$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'));

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


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

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

var_dump($metadata);
*/

参考 https://docs.mongodb.com/php-library/current/tutorial/gridfs/

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

最后更新于 2020年11月2日

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