1

I'm trying to get files and display them in my browser from Azure Blob Storage via an Azure function. I could manage to download the files when I navigate to the url but I couldn't display them as a static file/image in my browser.

I just want to display it in browser rather than downloading.

I've tried some sdk command but it didn't work. Here's what I've tried:

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
    ILogger log)
{
    var cloudStorageAccount =
        CloudStorageAccount.Parse(AzureStorageConnectionString);

    var cloudBlobClient =
        cloudStorageAccount.CreateCloudBlobClient();

    var cloudBlobContainer =
        cloudBlobClient.GetContainerReference(
            AzureStorageFilePath);

    await cloudBlobContainer.CreateIfNotExistsAsync();

    var blobName =
        req.Query["name"];

    var cloudBlockBlob =
        cloudBlobContainer.GetBlockBlobReference(blobName);

    var ms = new MemoryStream();

    await cloudBlockBlob.DownloadToStreamAsync(ms);

    return new FileContentResult(ms.ToArray(), cloudBlockBlob.Properties.ContentType);
}

Any ideas would be appreciated. Thanks!

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
TonyZhao79
  • 11
  • 2
  • as a side note: instead of building this all manually, I would recommend to use Input bindings for Functions. This will remove all the boilerplate storage SDK code https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-input?tabs=csharp – silent Jul 30 '20 at 07:53
  • My suggestion is for your endpoint to return a SAS Url to the blob if they're private or just the blob url and you serve that directly from the frontend. – lopezbertoni Jul 30 '20 at 21:19

1 Answers1

0

Kindly check the content type of the file(s) which you want to display ,if the content type is "application/octet-stream" it will cause the file to download. By default if content-type is not supplied azure sdk sets it as "application/octet-stream" which causes the file to download,set the correct content-type for the file ex :- for image it should be "image/jpeg". Hopefully this should fix the issue.

Aditya Singh
  • 137
  • 6
  • Unfortunately it won't because FileContentResult results a file. – Gaurav Mantri Jul 30 '20 at 07:38
  • @GauravMantri-AIS - Agreed the FileContentResult results in a file but if content type is set to "application/octet-stream" it will cause the file to be downloaded rather than it being displayed on the UI. Tried it by creating a simple controller action method which returned an image file and i could it see it being displayed as an image file on the browser with content type as image/jpeg. – Aditya Singh Jul 30 '20 at 08:06