Introduction
In this article, we will discuss Azure Storage and the different types of storage services provided by Azure. We will create a storage account from the Azure portal, and we will then create an Azure function to store the files in Azure blob storage, 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.
What is Azure Storage Service
Whenever we create an application, we have to first decide what storage we can use to store the data. Azure Storage provides solutions to different storage problems. It provides scalable, available, and durable storage for data in Azure. Azure storage is a set of different services such as Blobs, Files, Queues, etc. We can interact with Azure storage using different programming languages such as .NET, JAVA, Golang, Javascript, etc., using the SDKs.
Different Azure Storage Service
- Azure Blob: Also known as blobs which are mainly used to store binary/text data such as photos, videos, documents, etc.
- Azure Tables: This is nothing but a NoSQL storage for schemaless structured data.
- Azure Queue: It is used to store the messages which can be used to communicate with applications
- Azure Files: It is a 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 schema-less structured data in the cloud. We can store data such as documents, pictures, videos, log files, and backup files that don’t have a fixed structure. Blob storage is similar to a directory structure, where we can create different containers to store the blobs.
There are 3 types of Blobs
- Block Blobs: These are used to store the text/binary data.
- Append Blobs: Nothing but block blobs that are optimized for append operation.
- Page Blobs: These store random access files up to 8 TiB in size.
Create a 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 an Azure Storage resource using Azure Portal
Login to Azure and click on the Create a Resource button.
In the search box, type “storage account” and select it.
Click on the Create button, and you can see the Create storage account page.
Azure has Resource Groups (RG) that act as a container for your resources. So now we are going to create a Storage account resource. First, we need to create a 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 the storage account and select the region. Click on the Next: Advanced button.
By default, the “Enable blob public access” is checked, which means that any anonymous user can access blobs within the containers. So uncheck the option and click on the Review + Create button
Wait for a 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 the deployment process to finish.
Our storage account has been created successfully. Now click on the Go to Resource button to see the storage account.
Now the next step is to create a container to store our blobs. So in the left section, click on Containers and then click on the + Container button. Give the proper name to the container in which we are going to upload our files and click on the Create button.
The next step is to create an Azure function that uploads files into the “file-upload” container.
Create an 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, 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 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 an HTTP Trigger function, which takes a 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 the 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 the value of the “AzureWebJobsStorage” key. Also, add another key called “ContainerName” and paste the name of the container we 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 read the file request by using a key called “File” into the variable, and using the OpenReadStream() function, we read the file into the steam. To interact with Blob storage, we first have to create BlobContainerClient by passing the connection string and container name. After creating the client, we have to create BlobClient using the GetBlobClient method by passing the input file name.
Finally, to upload the file to the container, we used the UploadAsync method by passing the stream. You can read more about these 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 that we uploaded.
Publish Azure function to Azure function app using Visual Studio
Create a function app using the Azure portal
Log in to the Azure portal. In the Search bar, search "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 review all the details and click on the Create button. Wait for a few minutes to create the resources.
Once deployment is complete, click on the Go to Resource button to see our 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 the 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 the 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.