How can I store Images in Azure Cosmos DB?

12,193

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.

Share:
12,193
Ashish
Author by

Ashish

Updated on June 24, 2022

Comments

  • Ashish
    Ashish about 2 years

    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.