How to upload files into Azure Blog Storage using Azure functions in C#
Tags: azure, cloud, beginners, showdev
Published: 2022-04-11 17:06:42

​

## 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](https://dev.to/sumitkharche/how-to-easily-create-azure-functions-using-azure-portal-5ghd)
- [How To Create And Publish Azure Function From Visual Studio](https://dev.to/sumitkharche/how-to-easily-create-azure-functions-using-azure-portal-5ghd)
- [How To Integrate Application Insights Into Azure Functions](https://dev.to/sumitkharche/how-to-integrate-application-insights-into-azure-functions-4d1g)


## 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](https://portal.azure.com/) (If you don't have an Azure subscription, [create a free trial account](https://azure.microsoft.com/free))
 - Visual Studio 22 with Azure Development workload
 - Basic knowledge of C#
 

## Create a Azure Storage resource using Azure Portal

Login to [Azure  ](https://portal.azure.com/)and click on Create a resource button.
In search box type “storage account” and select it.

![stg-1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/je2wkleshvevguzd6oh4.png)
 
Click on Create button and you can see the Create storage account page.

![stg-2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5qk1b4ea72ce57qcmqj.png)
 
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.

![stg 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c06ara11rxz03mt9bj26.png)
 
Give the unique name to storage account and select the region. Click on Next : Advanced button.

![stg 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xs34xb4zcc24djk8tnnk.png)

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

![stg 5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gigaifyv72gjmu9i216d.png)
 
Wait for few sec to complete the validation and Review everything is added properly after that click on Create button.

![stg 6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ym06ijvw3oob57boxppf.png)

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

![stg 7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9c0p3rz6pf76d981quu.png)
 
Our storage account is created successfully. Now click on Go to resource button to see the storage account.

![stg 8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4p1774w7emhyejx6kwio.png)
 
![stg 9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkjok8krn26qk45iaxox.png)
 
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.

![stg 10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33o7xkwzapzn65uwv8hf.png)
 
Next step is to create a Azure function which upload files into the “file-upload” container.

![stg 11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irsw1a0n7c9414kgok93.png)
 

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

![fun-01](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2afao1y4kp6tqjuob2lc.png)
 

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

![fun 02](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbyk00kq6w67e0kzm6aq.png)
 

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

![fun 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dttpf087abjoertb7my5.png)
 

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

![fun 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mznar7y3ebkwi21djwch.png)
 
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.

![fun 5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpeqvjgki7l0cg6qymxr.png)

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.

```json
{
    "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.

![fun 6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5h619ww2w1t3mrq5xpk.png)
 

Now add the below code to upload a file into the container in our blob storage.

```csharp
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](https://github.com/Azure/azure-sdk-for-net).

Now run the FileUpload function.

![fun 7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rl3bfi2ifvuszthx6brx.png)
 
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.

![fun 8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zgovovd11vz1vj7fqmhm.png)
 
Now if we open our “file-upload” container we can see the file which we uploaded.

![fun 9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/negykxvlt3tp20p7rdc7.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymxldsxhs7t91tm6bt5r.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovwbs7mrdrf5vnvrgrlh.png)

After that click on the " + Create" button to add a new function app. Fill out the basic details:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqd5iia55kod6dvsvixt.png)
 
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.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cm2zy294rc2a0zxgssji.png)

Once deployment complete click on Go to resource button to see out new function app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9dh2v9zqbo05td5engfp.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02r7rx9q720dc5ieedud.png)
  
#### 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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8q7zpenei1365llfflz3.png)
 
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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/12lvhstyjse389as9fz7.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhz39woxyyhx4xe9k48a.png)
 

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sdrm2iqw0yk51f8mpbmf.png)
 
#### 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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6y4nr3xchcu2762luviu.png)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cq6dh9nfm8c82vddep4h.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pajt6ujwu6xb2goyees7.png)

Finally click on Save button to save changes. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ysqtqd3po2vdd45855jf.png) 

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czvuxirr9y5si9x1eirs.png)

Now as we test locally in form-data add a key "File" and select file you want to upload.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89p6fob1qx2gnmw7soo6.png)
 
Now if we check container we can see the file uploaded into it.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7awd4yt36yh20p66yxk.png)

## 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](https://twitter.com/sumitkharche01) or LinkedIn [Sumit Kharche](https://www.linkedin.com/in/sumit-kharche-890426a9/)

​Happy Coding!!!