Getting file type in Blob Storage bound Azure Function

Viewed 1392

I'm creating an Azure Function that is bound to my Azure Blob Storage container and triggers whenever a file is uploaded.

This particular container could have any type of file/blob in it e.g. image, PDF, Excel, MP4, etc.

I want to create different handlers that will do something depending on uploaded file type. For example, if it's an image file, I want to get its dimensions. If it's an MP4, I want to call another service to process the video, etc.

How do I get the file type from Stream? It's important to note that I cannot rely on file extension as in some cases, the extension may not be there. Is there a way for me to get the mimetype?

This is the standard BlogTrigger Azure Function code:

[FunctionName("FileManager")]
public static void Run([BlobTrigger("my-container/{name}", Connection = "myConnectionString")]Stream myBlob, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}
2 Answers

You can get these properties.

The Content-Type (if set when uploaded) is returned in metaData argument.

[FunctionName("SomeFunction")]
public async Task RunFunctionFaceDetection(
    [BlobTrigger("%PhotosContainerName%/{blobname}.{blobextension}", Connection = "storage-conn")]Stream inputBlob,
    string blobName, //blob name
    string blobExtension, //blob extension - file extension
    string blobTrigger, // full path to triggering blob
    Uri uri, // blob primary location
    IDictionary<string, string> metaData) // user-defined blob metadata
{
    _logger.LogInformation($"RunFunctionAWSFaceDetection just started...");
    _logger.LogInformation($@"
            blobName      {blobName}
            blobExtension {blobExtension}
            blobTrigger   {blobTrigger}
            uri           {uri}
            metaData      {metaData.Count}");

    _logger.LogInformation($"C# Blob trigger function processed blob\n Name:{blobName} \n Size: {inputBlob.Length} Bytes");
}

No, please use CloudBlockBlob to receive the blob:

using System;
using System.IO;
using System.Text;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;

namespace FunctionApp24
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([BlobTrigger("test/{name}", Connection = "str")] CloudBlockBlob myBlob, string name, ILogger log)
        {
            string a = myBlob.Properties.ContentType;
            log.LogInformation(a);
        }
    }
}

And you can use below code to convert the blob to stream:

Stream stream = new MemoryStream();
myBlob.DownloadToStreamAsync(stream).Wait();
Related