Introduction
In this article, we will discuss about Azure Storage and different types of storage services provided by azure. We will create a storage account from Azure portal and we will then create azure function to store the files into azure blob storage and finally we will deploy the same function to the Azure function app from Visual Studio.
If you are new to Azure Functions then check out the below articles,
- How To Easily Create Azure Functions Using Azure Portal
- How To Create And Publish Azure Function From Visual Studio
- How To Integrate Application Insights Into Azure Functions
What is Azure Storage Service
Whenever we create a application we have to first decide what storage we can use to store the data. Azure Storage provides solution to different storage solution problems. It provides scalable, available, durable storage for data in azure. Azure storage is set of different services such as Blobs, Files, queues, etc. We can interact with azure storage using different programming languages such .NET, JAVA, Golang, Javascript, etc. using the SDKs.
Different Azure Storage Service:
- Azure Blob - also know as blobs which mainly used to store the binary/text data such as photos, videos, documents, etc.
- Azure Tables - which is nothing but a NoSQL storage for schemaless structured data.
- Azure Queue - it is used to store the messages which can be use to communicate with applications
- Azure Files - it is managed file share service for cloud or on-premise using SMB/NFS protocol.
- Azure Disks - It is a virtual hard disk (VHD) that is of two types: managed and unmanaged.
What is Azure Blob storage
Azure Blob storage is a storage service used to store schemaless structured data in the cloud. We can store data such as documents, pictures, videos, log files, backup files which don’t have fixed structure. Blob storage are similar to directory structure where we can create different containers to store the blobs.
There are 3 types of Blobs:
- Block Blobs - which are used to store the text / binary data.
- Append Blobs - nothing but block blobs which are optimize for append operation.
- Page Blobs - which store random access files up to 8 TiB in size.
Create simple azure function using C# to upload files in Azure Blog Storage
Prerequisites:
- Azure account (If you don't have an Azure subscription, create a free trial account)
- Visual Studio 22 with Azure Development workload
- Basic knowledge of C#
Create a Azure Storage resource using Azure Portal
Login to Azure and click on Create a resource button.
In search box type “storage account” and select it.
Click on Create button and you can see the Create storage account page.
Azure has Resource Groups (RG) which acts as a container for your resources. So now we are going to create a Storage account resource. First we need to create Resource Group. If you have already created RG then you can use the same here. Under Resource group click on Create New button and give a unique RG name.
Give the unique name to storage account and select the region. Click on Next : Advanced button.
By default the “Enable blob public access” is checked which means that any anonymous user can access to blobs within the containers. So uncheck the option and click on Review + Create button
Wait for few sec to complete the validation and Review everything is added properly after that click on Create button.
Creating resources will take time so wait for deployment process to finish.
Our storage account is created successfully. Now click on Go to resource button to see the storage account.
Now next step is to create container to store our blobs. So in left section click on Containers and then click on + Container button. Give the proper name to container in which we are going to upload our files and click on Create button.
Next step is to create a Azure function which upload files into the “file-upload” container.
Create a HTTP trigger azure function using C# to upload files to blob storage
So open Visual Studio and Go to File -> New -> Project. Search "Azure Functions" in the search box and select the Azure function template and click on Next.
Give a name to the function project and click on Create.
Select the HTTP trigger template and set the Authorization level as Anonymous and click on Create.
That's it. We have created our first Azure function. By default the name of the function is Function1.cs so now change it to "FileUpload".
So for our application, we are creating HTTP Trigger function which takes file as input and uploads it into the Azure Blob. To connect with the Blob Storage container we need a connection string. So let's open the Azure Storage resource in portal ->Access Keys -> Click on Show Keys - > Copy the Key 1 Connection String.
Open the local.settings.json file in our function app and paste the connection string of our Azure Storage resource as value of “AzureWebJobsStorage” key. Also add another key called as “ContainerName” and paste the name of container we have created earlier.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<replace your blob storage connection key here>",
"ContainerName": "file-upload", // Container name
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
To interact with Azure storage we have to first install the below NuGet package.
Now add the below code to upload a file into the container in our blob storage.
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading.Tasks;
namespace FileUploadFunction
{
public static class FileUpload
{
[FunctionName("FileUpload")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
ILogger log)
{
string Connection = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
string containerName = Environment.GetEnvironmentVariable("ContainerName");
Stream myBlob = new MemoryStream();
var file = req.Form.Files["File"];
myBlob = file.OpenReadStream();
var blobClient = new BlobContainerClient(Connection, containerName);
var blob = blobClient.GetBlobClient(file.FileName);
await blob.UploadAsync(myBlob);
return new OkObjectResult("file uploaded successfylly");
}
}
}
First we have stored the Blob Storage connection string and container name from configuration into local variables. After that we have read the file request by using key called “File” into variable and using OpenReadStream() function we have read the file into the steam. To interact with Blob storage we first have to create BlobContainerClient by passing connection string and container name. After creating client, we have to create BlobClient using GetBlobClient method by passing input file name.
Finally to upload file to container we have used UploadAsync method by passing steram. You can read more about this methods here.
Now run the FileUpload function.
For testing the function open postman and paste the about function URL i.e. http://localhost:7071/api/FileUpload
Now in our code we have read the file from form data so click on Body and select form-data then add key as “File” and for value select which file you want to upload and click on Send button.
Now if we open our “file-upload” container we can see the file which we uploaded.
Publish Azure function to Azure function app using Visual Studio
Create a function app using Azure portal
Log in to the Azure portal In the Search bar, search as "function app" and then select the Function app.
After that click on the " + Create" button to add a new function app. Fill out the basic details:
Now click on Review: Create button and review all the details and click on the Create button. Wait for a few minutes to create the resources.
Once deployment complete click on Go to resource button to see out new function app.
Publish the azure function into the function app
To deploy our function to Azure we need Azure Function App. Right Click on our solution and click on the Publish button.
As we are publishing into Azure then Select Azure and click on Next. Select target as "Azure Function App(Windows)" and click on Next. We can either select an already created function app or we can create a new Function app. Click on Finish button.
Click on Publish button to push our function to our Function App.
Once our app is successfully published on Azure, go to the Azure portal and search for our function app. Select Functions from the left sidebar to see our deployed function.
Configure the storage account connection string into Configuration setting of Function app
Now we have deployed our function into Function app so next step is to configure the settings. So click on Configuration. For this app we have to set value of Storage connection string and container name in configuration. So seach for "AzureWebJobsStorage" and click on Edit button and paste your storage connection string.
Click on "+ New application setting" and give name as "ContainerName" and Value as "file-upload".
Finally click on Save button to save changes.
Test publish app using postman
To ge the url of deployed function click on Functions -> Select File Upload function -> Click on Get Function Url -> Copy url and paste in postman.
Now as we test locally in form-data add a key "File" and select file you want to upload.
Now if we check container we can see the file uploaded into it.
Conclusion
In this article, we have discuss about Azure Storage and Azure blob storage. We have created a Azure Blob storage resource from Azure Portal. We created a new Azure function from Visual Studio which uploads the file to blob storage. Also, I demonstrated how to test and deploy the function from VS and test using Postman.
I really hope that you enjoyed this article, share it with friends, and please do not hesitate to send me your thoughts or comments. Stay tuned for more Azure Functions articles.
You can follow me on twitter @sumitkharche01 or LinkedIn Sumit Kharche
Happy Coding!!!
Top comments (0)