Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
niio972 opened this issue Mar 14, 2018 · 0 comments
Open

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

niio972 opened this issue Mar 14, 2018 · 0 comments

Comments

@niio972
Copy link
Member

niio972 commented Mar 14, 2018

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant