gpt4 book ai didi

java - 如何覆盖 mongoDB gridfs 中的图像?

转载 作者:IT老高 更新时间:2023-10-28 12:31:25 28 4
gpt4 key购买 nike

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

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)

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

最佳答案

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

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);
}

关于java - 如何覆盖 mongoDB gridfs 中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223691/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com