如何使用Spring Data MongoDB通过GridFS ObjectId获取二进制流
当我已经拥有正确的ObjectId
时,我不知道如何使用spring-data-mongodb及其GridFSTemplate
从GridFS流式传输二进制文件.
I can't figure out how to stream a binary file from GridFS with spring-data-mongodb and its GridFSTemplate
when I already have the right ObjectId
.
GridFSTemplate返回GridFSResource
(getResource()
)或GridFSFile
(findX()
).
GridFSTemplate returns either GridFSResource
(getResource()
) or GridFSFile
(findX()
).
我可以通过ID获取GridFSFile
:
// no way to get the InputStream?
GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)))
,但是没有明显的方法为该GridFSFile
获取InputStream
.
but there is no obvious way how to get an InputStream
for that GridFSFile
.
只有GridFSResource
允许我掌握InputStreamResource#getInputstream
对应的InputStream
.但是获取GridFSResource
的唯一方法是通过其filename
.
Only GridFSResource
allows me to get hold of the corresonding InputStream
with InputStreamResource#getInputstream
. But the only way to get a GridFSResource
is by its filename
.
// no way to get GridFSResource by ID?
GridFSResource resource = gridFsTemplate.getResource("test.jpeg");
return resource.getInputStream();
以某种方式GridFsTemplate
API意味着文件名是唯一的-不是. GridFsTemplate
实现仅返回第一个元素.
Somehow the GridFsTemplate
API implies that filenames are unique - which they are not. The GridFsTemplate
implementation just returns the first element.
现在我正在使用本机MongoDB API,一切又变得有意义了:
Now I'm using the native MongoDB API and everything makes sense again:
GridFS gridFs = new GridFs(mongo);
GridFSDBFile nativeFile = gridFs.find(blobId);
return nativeFile.getInputStream();
似乎我误解了Spring Data Mongo GridFS抽象背后的基本概念.我希望(至少)以下其中一项可能/正确:
It looks like I'm misunderstanding the fundamental concepts behind the Spring Data Mongo GridFS abstraction. I'd expect (at least) one of the following things to be possible/true:
- 通过其ID获取
GridFSResource
- 为我已经拥有的
GridFsFile
获取GridFSResource
或InputStream
- get a
GridFSResource
by its ID - get a
GridFSResource
orInputStream
for aGridFsFile
I already have
我错了吗?Spring Data MongoDB API的这一特定部分是否有些奇怪?
Am I wrong or is there something odd with this particular piece of the Spring Data MongoDB API?
我也偶然发现了这一点.实际上,令GridFsTemplate如此设计感到非常震惊... 无论如何,到目前为止我的丑陋解决方案":
I stumbled upon this, too. And I am actually pretty shocked that the GridFsTemplate has been designed like this... Anyway, my ugly "solution" to this so far:
public GridFsResource download(String fileId) {
GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
return new GridFsResource(file, getGridFs().openDownloadStream(file.getObjectId()));
}
private GridFSBucket getGridFs() {
MongoDatabase db = mongoDbFactory.getDb();
return GridFSBuckets.create(db);
}
注意:您必须注入MongoDbFactory才能使其工作...
Note: You have to inject the MongoDbFactory for this to work...