How To Upload Files Into Azure Blob Storage Using Azure Functions In C#

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

  1. Azure Blob: Also known as blobs which are mainly used to store binary/text data such as photos, videos, documents, etc.
  2. Azure Tables: This is nothing but a NoSQL storage for schemaless structured data.
  3. Azure Queue: It is used to store the messages which can be used to communicate with applications
  4. Azure Files: It is a managed file share service for cloud or on-premise using SMB/NFS protocol.
  5. 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

  1. Block Blobs: These are used to store the text/binary data.
  2. Append Blobs: Nothing but block blobs that are optimized for append operation.
  3. 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

  1. Azure account (If you don't have an Azure subscription, create a free trial account)
  2. Visual Studio 22 with Azure Development workload
  3. 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.

AzureAccounts

Click on the Create button, and you can see the Create storage account page.

CreateStorageAccount

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.

InstanceDetails

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

Blob Public Access

Wait for a few sec to complete the validation and Review. Everything is added properly. After that click on Create button.

Encryption

Creating resources will take time, so wait for the deployment process to finish.

Deployment

Our storage account has been created successfully. Now click on the Go to Resource button to see the storage account.

DeploymentSuccess

Essentials

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.

containers

The next step is to create an Azure function that uploads files into the “file-upload” container.

fileupload

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.

AzureFunction

Give a name to the function project and click on Create.

FileUploadFunction

Select the HTTP trigger template set the Authorization level as Anonymous, and click on Create.

NewAzureFunction

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".

CodeFile 1

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.

Access Keys

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.

AzureStorageBlob

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.

AzureTerminal

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.

PostmanFormData

Now if we open our “file-upload” container, we can see the file that we uploaded.

FileuploadMethod

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.

AzureAppFunction

FunctionCreate

After that, click on the " + Create" button to add a new function app. Fill out the basic details,

FunctionGroupDetails

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.

DeploymentProgress

Once deployment is complete, click on the Go to Resource button to see our new function app.

How to upload files into Azure Blog Storage using Azure functions in C#

How to upload files into Azure Blog Storage using Azure functions in C#

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.

How to upload files into Azure Blog Storage using Azure functions in C#

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.

How to upload files into Azure Blog Storage using Azure functions in C#

Click on Publish button to push our function to our Function App.

How to upload files into Azure Blog Storage using Azure functions in C#

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.

How to upload files into Azure Blog Storage using Azure functions in C#

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.

How to upload files into Azure Blog Storage using Azure functions in C#

How to upload files into Azure Blog Storage using Azure functions in C#

Click on "+ New application setting" and give name as "ContainerName" and Value as "file-upload".

How to upload files into Azure Blog Storage using Azure functions in C#

Finally click on Save button to save changes. 

How to upload files into Azure Blog Storage using Azure functions in C#

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.

How to upload files into Azure Blog Storage using Azure functions in C#

Now as we test locally in form-data add a key "File" and select file you want to upload.

How to upload files into Azure Blog Storage using Azure functions in C#

Now if we check container we can see the file uploaded into it.

How to upload files into Azure Blog Storage using Azure functions in C#

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.


Similar Articles