MongoDB GridFS按ID查找文件

问题描述 投票:0回答:1

我正在使用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搜索文件时如何实现相同的目的?

php laravel mongodb gridfs
1个回答
0
投票

您可以使用openDownloadStream通过其id选择文件。

docs

MongoDB\GridFS\Bucket::openDownloadStream

通过_id选择GridFS文件,并将其作为可读流打开。

因此,在您的情况下,如下所示:

$bucket = DB::getMongoDB()->selectGridFSBucket();
$stream = $bucket->openDownloadStream('5d89ff86740f35501419d7f2');
© www.soinside.com 2019 - 2024. All rights reserved.