1

I am looking for a sample or IP for updating a blob's metadata when it is uploaded. All help is appreciated.

I have following function:

public static void Run([BlobTrigger("types/{name}", Connection = "StorageConnection")]Stream myBlob, string name, ILogger log)
{
}

1 Answer 1

4

You can use the trigger to get the ICloudBlob instead of the stream.
Check the official documentation on blob triggers for Azure Functions.

Basically, your code will look something like this:

public static void Run(
    [BlobTrigger("types/{name}", Connection = "StorageConnection")] ICloudBlob myBlob, 
    string name, 
    ILogger log)
{
    if (blobTrigger.Metadata.ContainsKey("MyKey"))
        return;

    blobTrigger.Metadata["MyKey"] = "MyValue";
    await blobTrigger.SetMetadataAsync();
}

There is an issue though. After you update your metadata, you are basically uploading the blob again, which in turn, will trigger your function again.

I've added a simple check to see if my metadata key was already added to avoid an infinite loop.
Of course, you will probably have your own way of knowing if you are the one who just updated the metadata or not. Worst case scenario, you'll have to use your own flag to indicate that the upload occurred from your function.

Hope it helps. :)

Sign up to request clarification or add additional context in comments.

5 Comments

Do you then have to query for the specific blob? There is not way to edit the current blob directly? I hoped from a performance perspectice I would get a direct reference to current blob.
Oh, I guess I misunderstood your question. You can use an ICloudBlob as your trigger binding, which will give you access to the blob itself, and then you can save it in the container or you can simply use an output binding to save it. I'll update the answer.
Updated the answer with an actually simpler approach. Let me know if it doesn't work for you.
I really like the code. However just tested it and I get that exact problem with the infinite loop. I will try to dig into it. In my sample the metadata is there when uploaded. So I get that exact situation :(
I tried that and got this beauty. Binds to stream just fine. [2021-10-14T02:22:45.470Z] Microsoft.Azure.WebJobs.Host: Error indexing method 'BlobTriggerFunction'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'cloudBlob' to type ICloudBlob. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.