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:
- An Azure account
- Azure Storage account
- Azure Functions app
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.
- Go to the Azure portal.
- Select Create a resource and then Storage account.
- Fill in the necessary details (Subscription, Resource group, Storage account name, etc.).
- Review and create the storage account.
2. Create an Azure Functions App
- In the Azure portal, select Create a resource and then Function App.
- 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.
- Review and create the Function App.
3. Create a Function to Upload Files
- 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
- Run the application.
- Get the function URL
- Use a tool like Postman or cURL to send a POST request with a file to the function URL.
- Open the storage account to see the file is uploaded successfully.
No Comment! Be the first one.