我正在使用MongoDB GridFS来存储文件。我正在尝试实施解决方案,以便能够通过名称和ID查找文件
查找文件并返回非常简单。
$bucket = DB::getMongoDB()->selectGridFSBucket();
$stream = $bucket->openDownloadStreamByName('file_name.pdf', ['revision' => 0]);
contents = stream_get_contents($stream);
return response($contents)
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'attachment; filename="file_name.pdf"');
[如果我仅知道文件ID(例如:5d89ff86740f35501419d7f2),则通过ID搜索文件时如何实现相同的目的?
您可以使用openDownloadStream
通过其id
选择文件。
从docs:
MongoDB\GridFS\Bucket::openDownloadStream
通过_id选择GridFS文件,并将其作为可读流打开。
因此,在您的情况下,如下所示:
$bucket = DB::getMongoDB()->selectGridFSBucket();
$stream = $bucket->openDownloadStream('5d89ff86740f35501419d7f2');