Attachments: Storing Attachments
In order to store an attachment in RavenDB you need to create a document. Then you can attach an attachment to the document using the session.advanced().attachments().store
method.
Attachments, just like documents, are a part of the session and will be only saved on the Server when DocumentSession.saveChanges
is executed (you can read more about saving changes in session here).
Syntax
Attachments can be stored using one of the following session.advanced().attachments().store
methods:
void store(String documentId, String name, InputStream stream);
void store(String documentId, String name, InputStream stream, String contentType);
void store(Object entity, String name, InputStream stream);
void store(Object entity, String name, InputStream stream, String contentType);
Example
try (IDocumentSession session = store.openSession()) {
try (
FileInputStream file1 = new FileInputStream("001.jpg");
FileInputStream file2 = new FileInputStream("002.jpg");
FileInputStream file3 = new FileInputStream("003.jpg");
FileInputStream file4 = new FileInputStream("004.mp4")
) {
Album album = new Album();
album.setName("Holidays");
album.setDescription("Holidays travel pictures of the all family");
album.setTags(new String[] { "Holidays Travel", "All Family" });
session.store(album, "albums/1");
session.advanced().attachments()
.store("albums/1", "001.jpg", file1, "image/jpeg");
session.advanced().attachments()
.store("albums/1", "002.jpg", file2, "image/jpeg");
session.advanced().attachments()
.store("albums/1", "003.jpg", file3, "image/jpeg");
session.advanced().attachments()
.store("albums/1", "004.mp4", file4, "video/mp4");
session.saveChanges();
}
}