DEV Community

Cover image for Load & view a document from Azure Blob Storage
Atir Tahir
Atir Tahir

Posted on

1

Load & view a document from Azure Blob Storage

How about loading a document/file from cloud such as Azure and rendering it in browser directly (whiteout any need to download the source file to local storage). However, we'll download and save the file to MemoryStream.
We'll use GroupDocs.Viewer API to render or view the document. This back-end API could be integrated in any .NET application without any third party tool or software dependency.
How document viewer API works:

string blobName = "sample.docx";
using (Viewer viewer = new Viewer(() => DownloadFile(blobName)))
{
    HtmlViewOptions viewOptions = HtmlViewOptions.ForEmbeddedResources();                
    viewer.View(viewOptions);
}
Enter fullscreen mode Exit fullscreen mode

Let's fetch the source file:

public static Stream DownloadFile(string blobName)
{
    CloudBlobContainer container = GetContainer();
    CloudBlob blob = container.GetBlobReference(blobName);
    MemoryStream memoryStream = new MemoryStream();
    blob.DownloadToStream(memoryStream);
    memoryStream.Position = 0;
    return memoryStream;
}
Enter fullscreen mode Exit fullscreen mode

Setting up and returning container:

private static CloudBlobContainer GetContainer()
{
    string accountName = "***";
    string accountKey = "***";
    string endpoint = $"https://{accountName}.blob.core.windows.net/";
    string containerName = "***";
    StorageCredentials storageCredentials = new StorageCredentials(accountName, accountKey);
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(
    storageCredentials, new Uri(endpoint), null, null, null);
    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = cloudBlobClient.GetContainerReference(containerName);
    container.CreateIfNotExists();
    return container;
}
Enter fullscreen mode Exit fullscreen mode

For further details or assistance post here at free support forum.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay