Introduction

Azure Blob Storage is a scalable object storage service for unstructured data such as text or binary data. It’s ideal for storing files, images, videos, and backups. Azure Functions provide a serverless compute service that allows you to run small pieces of code, or “functions,” in response to events. In this blog post, we will walk you through the steps to upload files to Azure Blob Storage using Azure Functions.

Prerequisites

Before we start, ensure you have the following:

Step-by-Step Guide

1. Create an Azure Storage Account

First, you need to create a storage account if you don’t already have one.

  1. Go to the Azure portal.
  2. Select Create a resource and then Storage account.
  3. Fill in the necessary details (Subscription, Resource group, Storage account name, etc.).
  4. Review and create the storage account.

2. Create an Azure Functions App

  1. In the Azure portal, select Create a resource and then Function App.
  2. Fill in the required fields:
    • Subscription: Your Azure subscription.
    • Resource Group: Create a new resource group or use an existing one.
    • Function App Name: A unique name for your Function App.
    • Runtime Stack: Choose your preferred runtime (e.g., .NET Core, Node.js, Python).
    • Region: Select the region closest to you.
  3. Review and create the Function App.

3. Create a Function to Upload Files

  1. In your local development environment, create a new Azure Functions project.

2.Install the Azure Storage Blob client library.

3.Modify the generated function code to upload a file to Blob Storage.

using Azure.Identity;
using Azure.Storage.Blobs;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System;
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)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // Validate the request
            var formCollection = await req.ReadFormAsync();
            var file = formCollection.Files[0];
            var containerName = "my-container";
            var blobName = "my-blob";

            if (file == null || string.IsNullOrEmpty(containerName) || string.IsNullOrEmpty(blobName))
            {
                return new BadRequestObjectResult("File, container name, or blob name is missing.");
            }

            try
            {
                // Upload the file to the blob
                string result = await UploadFileToBlob(file, containerName, blobName);
                return new OkObjectResult(new { BlobUri = result });
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Error uploading file to blob storage.");
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
        }

        public static async Task<string> UploadFileToBlob(IFormFile file, string containerName, string blobName)
        {
            var storageAccountName = "my-storage-account";
            var tenantId = "my-tenantId";

            if (string.IsNullOrEmpty(storageAccountName) || string.IsNullOrEmpty(tenantId))
            {
                throw new InvalidOperationException("Storage account name or tenant ID is not set in environment variables.");
            }

            var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
            {
                VisualStudioTenantId = tenantId
            });

            var blobServiceClient = new BlobServiceClient(new Uri($"https://{storageAccountName}.blob.core.windows.net"), credential);
            var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);

            // Check if the container exists
            bool containerExists = await blobContainerClient.ExistsAsync();

            if (!containerExists)
            {
                // Create the container if it does not exist
                await blobContainerClient.CreateAsync();
            }

            var blobClient = blobContainerClient.GetBlobClient(blobName);

            // Upload the file to the blob
            using (var stream = file.OpenReadStream())
            {
                await blobClient.UploadAsync(stream, true);
            }

            // Return the URI of the uploaded blob
            return blobClient.Uri.ToString();
        }
    }
}

4. Test the Function

  1. Run the application.
  2. Get the function URL
  3. Use a tool like Postman or cURL to send a POST request with a file to the function URL.
  4. Open the storage account to see the file is uploaded successfully.

Conclusion

You’ve now successfully created an Azure Function that uploads files to Azure Blob Storage. This setup can be extended to handle various types of data and integrated into larger applications. Azure Functions and Blob Storage provide a powerful combination for serverless computing and scalable storage solutions. Happy coding!

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.