Skip to content

Get or save file directly in Mongo with an InputStream object #40

@niio972

Description

@niio972

Maybe use UploadFromStream from mongo driver 3.6. Prevent the use of temporary directory.

http://mongodb.github.io/mongo-java-driver/3.6/driver/tutorials/gridfs/
Save
// Get the input stream

try {
    InputStream streamToUploadFrom = new FileInputStream(new File("/tmp/mongodb-tutorial.pdf"));
    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions()
                                        .chunkSizeBytes(358400)
                                        .metadata(new Document("type", "presentation"));

    ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, options);
} catch (FileNotFoundException e){
   // handle exception
}

Load

ObjectId fileId; //The id of a file uploaded to GridFS, initialize to valid file id 

try {
    FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.pdf");
    gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
    streamToDownloadTo.close();
    System.out.println(streamToDownloadTo.toString());
} catch (IOException e) {
    // handle exception
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions