DEV Community

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

Posted on

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.

Top comments (0)