How can I store Images in Azure Cosmos DB?

Ashish picture Ashish · Mar 18, 2018 · Viewed 8.3k times · Source

I have PNG images which i want to store in cosmos db along with some metadata. What is the best way to store it ? I don't want to store in Azure blob storage separately, better to store with the data.

Answer

Sajeetharan picture Sajeetharan · Mar 18, 2018

If you want to store images directly to the cosmos db, you can use DocumentClient.CreateAttachmentAsync method to store it directly.

using (FileStream fileStream = new FileStream(@".\something.pdf", FileMode.Open))
{
    //Create the attachment
    Attachment attachment = await client.CreateAttachmentAsync("dbs/db_rid/colls/coll_rid/docs/doc_rid/attachments/", 
    fileStream, 
    new MediaOptions 
    { 
       ContentType = "image/jpeg", 
       Slug = "myImage.jpeg" 
    });
}

There's nothing inherently built-in to manage externally-stored attachments. Rather, it's up to you to store them and then reference them.

The most common pattern is to store a URL to the specific attachment, with a document (e.g. to a blob in Azure Storage).

NOTE: Generally you are adding images into CosmosDB, it will costs you much for queries. Recommended way is to do is to store the image in Azure Blob and add the link in the Cosmos DB document you can take advantage of things like Azure CDN that will make your images load faster for your mobile.