In previous post we saw how to create azure function for HttpTrigger. Now lets see another use of azure function.
Scenario - Suppose you are uploading file in blob either directly from azure portal or through .net code and after upload you want to create thumbnail or resize that file . For this if you will do during upload in .net code then it might take time and user will not be happy with system performance . So to tackle such kind of scenario azure has provided BlobTrigger function. which automatically trigger and resize your file after uploading in blob. if you want to know more about azure function from start please see the previous post.
So Lets see how we can achieve this.
1. Open Visual Studio -> Create New Project -> Search for Azure functions Templates and click Next
1.Enter project name “AzureFunBlobTrigger” and click Next
2.In next section you need to select Trigger Type ,so select Blob Trigger and keep storage emulator in right side , if you want to use azure storage you can browse and choose.
Local.settings.json : In this file configure storage account and runtime framework. It has key-value code. open this file and paste the below code
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "your storgate connection string",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"fnBlob": "your storgate connection string"
}
}
fnBlob is the key which you are going to use for blob connection.
Function1.cs: Open the function.cs and paste the below code
L Lets understand the below code block
[FunctionName("Function1")] - function name which you can change with any name .
[BlobTrigger("mycontainer/{name}" -BlobTrigger is the attribute which trigger the function when any file will get upload in container "mycontainer".
Connection = "fnBlob")] - storage connection string name which I have defined in local.setting.json
[Blob("resized/{name}", another container where file will be save after resizing. you dont need to create ,it will be automatically created if not.
In the above code I have created one function called ResizeImage where I am passing input blob(which has been uploaded ,output blob path and name , size.
To resize image I am using nuget package called SixLabors.ImageSharp which you can add from package manager. I found this package more clean ,fast and easy to implement.
Thats all about coding part.
Lets try to upload file in container from azure portal and see what happens
L 1. Login to azure portal and go to storage account -> container -> mycontainer -> select upload and upload one file. as soon as you upload your file automatically your function will trigger in your local visual studio and resize the file and save in the output folder.
Before that just run your project from visual studio . you will see below logs if your function run successfully in vs.
No comments:
Post a Comment
Thanks for your valuable comments