首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在mongoDB gridfs中覆盖图片?

如何在mongoDB gridfs中覆盖图片?
EN

Stack Overflow用户
提问于 2016-12-19 21:28:48
回答 1查看 3.2K关注 0票数 7

我使用的是Java3.2和MongoDB 1.8版本以及mongo-java驱动程序。我已经在数据库中保存了图像。我能够保存图像,读取图像和读取所有图像。现在我想在GridFS中更新图像。如果镜像名称相同,我想覆盖镜像。当我尝试以相同的名称保存图像时,我得到了两个图像。我使用下面的代码来保存图像。

代码语言:javascript
复制
GridFSBucket gridFSBucket = GridFSBuckets.create(database, imageCollection);
        InputStream streamToUploadFrom = new FileInputStream(new File(imageFileName));
        GridFSUploadOptions options = new GridFSUploadOptions()
                .metadata(new Document("type", "brand").append("name", name).append("uuid", UUID.randomUUID().toString()));
        ObjectId fileId = gridFSBucket.uploadFromStream(name, streamToUploadFrom, options)

任何人可以引导我到任何特定的文档链接/解决办法,以便我可以覆盖/更新图像。

EN

回答 1

Stack Overflow用户

发布于 2016-12-20 17:53:25

无法在GridFS中更新文件。每个文档实际上被分成块,并且更新文件是不可能的。因此,我建议先删除要更新的文件,然后再导入新文件。

代码语言:javascript
复制
GridFSBucket gridFSBucket = GridFSBuckets.create(database, imageCollection);

GridFSBucket gridFSBucket = GridFSBuckets.create(database, imageCollection);
InputStream streamToUploadFrom = new FileInputStream(new File(new_image_file));

Document query = new Document("metadata.name", "image1");
MongoCursor<Document> cursor = database.getCollection(imagecollection+".files").find(query).iterator();

while (cursor.hasNext()) {
    Document document = cursor.next();
    Document metadata = document.get("metadata", Document.class);

    ObjectId _id = document.getObjectId("_id");
    gridFSBucket.delete(_id);

    GridFSUploadOptions options = new GridFSUploadOptions().metadata(metadata);
    ObjectId fileId = gridFSBucket.uploadFromStream("image1", streamToUploadFrom, options);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41223691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档