使用GridFS Java保存附件

时间:2018-05-16 14:39:05

标签: java mongodb gridfs mongo-java-driver

我正在尝试使用GridFS(Java驱动程序)将文件保存到Mongo。我遇到了多个指南,这些指南都有不同的实现,但我仍然有点困惑。我在我当前的实现中有这个,但是我很难拔出其他指南使用GridFSBucket对象获取的ObjectId。

    @Override
public <T> ObjectId uploadAttachment(String fileName, InputStream inputStream, String userName, Date timeOfUpload) {
    // Using depricated method because GridFS support in the new API didnt make the schedule for the 3.0 release but should be in 3.1.
    // https://stackoverflow.com/questions/29255474/to-construct-gridfs-objects-with-mongo-java-driver-v3-0-released
    ObjectId attachmentId = null;
    MongoClient mongoClient = new MongoClient();

    MongoDatabase db = mongoClient.getDatabase(MongoDBFactory.DATABASE_NAME);

    // GridFSBucket gfsBucket = GridFSBuckets.create(db, MongoDBFactory.ATTACHMENTS);
    // GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(255000);

    // gets caught here before timing out
    // attachmentId = gfsBucket.uploadFromStream(fileName, inputStream, options);

    DB database = mongoClient.getDB(MongoDBFactory.DATABASE_NAME);
    GridFS gridFS = new GridFS(database);
    GridFSInputFile inputFile = gridFS.createFile(inputStream, fileName);
    inputFile.put("documentName", fileName);
    inputFile.put("user", userName);
    inputFile.put("uploadDate", timeOfUpload);
    inputFile.save();

    mongoClient.close();

    return attachmentId;
}

注释掉的GridFS内容是其他指南用来获取在文件上传到fs.files和fs.chunks集合后返回的ObjectId的内容。我的问题是,如何在不使用GridFSBuckets的情况下获取ObjectId?或者是使用GridFSBucket获取上传文件的Id的唯一方法?

补充:我是否必须将上传的附件存储在自己的收藏中?或者我可以将它们作为属性存储在集合中的现有文档中吗?

指向指南的链接: https://www.mkyong.com/mongodb/java-mongodb-save-image-example/ https://blog.codecentric.de/en/2012/11/mongodb-supplemental-gridfs-example-in-java/ http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/gridfs/#uploadfromstream

谢谢!

0 个答案:

没有答案