0

I am currently working on a website that will download a Blob file from the Azure Blob Storage and displayed as an image. The file has been saved as Base64 and I am having issues downloading the file to the stream. I try multiple ways and everything leads to no result. This is what I have so far:

[HttpGet]
    public async IActionResult ViewFile(string name)
    {

        BlobServiceClient blobServiceClient = new BlobServiceClient(System.Environment.GetEnvironmentVariable("BlobConnection"));

        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("store-images");

        // this will allow us access to the file inside the container via the file name
        //var blob = containerClient.GetBlobs(prefix: name);

        //var blobContainerUri = containerClient.GetBlobClient(name);

        BlobClient blob = containerClient.GetBlobClient(name);

        MemoryStream stream = new MemoryStream();

        await blob.DownloadStreamingAsync(stream);

        stream.Position = 0;

        return stream;
    }
Robby
  • 197
  • 1
  • 2
  • 14
  • 1
    Please edit your question and include the code you tried and the issues you’re running into. As of now we simply don’t know what all things you’ve tried. – Gaurav Mantri Aug 18 '21 at 16:29
  • How are you consuming the stream? Can you share that code? – Gaurav Mantri Aug 18 '21 at 16:49
  • I am super new to this, the other code I have is just a HTML view. That is what I have for my controller. @GauravMantri – Robby Aug 18 '21 at 16:57

1 Answers1

2

Here is the logic that worked for me

string storageAccount_connectionString = "**Enter Connection String**";

CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference(azure_ContainerName);
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filetoDownload);           

// provide the file download location below            
Stream file = File.OpenWrite(@"C:\location" + filetoDownload);

cloudBlockBlob.DownloadToStream(file);
file.Close();

//Converting Base64 to png
string base64String = File.ReadAllText(@"C:\location\base64.txt");
byte[] imgBytes = Convert.FromBase64String(base64String);

using (var imageFile = new FileStream(@"C:\location\sample.png", FileMode.Create))
{
       imageFile.Write(imgBytes, 0, imgBytes.Length);
       imageFile.Flush();
}

References : Blog to convert base64 to png

Download blob from storage

SwethaKandikonda
  • 7,513
  • 2
  • 4
  • 18