Azure Storage Blobs Samples

Explore practical code examples and quickstarts for interacting with Azure Blob Storage. These samples demonstrate common operations like uploading, downloading, listing, and managing blobs.

Upload a Blob (C#)

This sample demonstrates how to upload a block blob to Azure Storage.


using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;
using System.Threading.Tasks;

public class BlobUploadSample
{
    public static async Task UploadBlobAsync(string connectionString, string containerName, string blobName, string filePath)
    {
        // Create a BlobServiceClient object which will be used to create a container client
        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

        // Get a client that will be used to interact with a specific blob
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

        // Get a client that will be used to interact with a specific blob
        BlobClient blobClient = containerClient.GetBlobClient(blobName);

        using (FileStream uploadFileStream = File.OpenRead(filePath))
        {
            await blobClient.UploadAsync(uploadFileStream, true);
            Console.WriteLine($"Uploaded blob '{blobName}' to container '{containerName}' from file '{filePath}'.");
        }
    }

    public static async Task Main(string[] args)
    {
        // Replace with your actual connection string, container name, blob name, and file path
        string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
        string containerName = "my-blob-container";
        string blobName = "my-uploaded-blob.txt";
        string filePath = "path/to/your/local/file.txt";

        if (string.IsNullOrEmpty(connectionString))
        {
            Console.WriteLine("Please set the AZURE_STORAGE_CONNECTION_STRING environment variable.");
            return;
        }

        // Ensure the container exists (optional, but good practice)
        try
        {
            var containerClient = new BlobContainerClient(connectionString, containerName);
            await containerClient.CreateIfNotExistsAsync();
            Console.WriteLine($"Container '{containerName}' is ready.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error creating or accessing container: {ex.Message}");
            return;
        }

        if (!File.Exists(filePath))
        {
            Console.WriteLine($"Error: File not found at '{filePath}'.");
            return;
        }

        await UploadBlobAsync(connectionString, containerName, blobName, filePath);
    }
}
                

Upload a Blob (Python)

This sample demonstrates how to upload a block blob to Azure Storage.


import os
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

def upload_blob(connection_string, container_name, blob_name, file_path):
    """Uploads a file to a blob container."""
    try:
        blob_service_client = BlobServiceClient.from_connection_string(connection_string)
        container_client = blob_service_client.get_container_client(container_name)

        with open(file_path, "rb") as data:
            blob_client = container_client.upload_blob(name=blob_name, data=data, overwrite=True)
            print(f"Uploaded blob '{blob_name}' to container '{container_name}' from file '{file_path}'.")
            return blob_client.url
    except Exception as e:
        print(f"Error uploading blob: {e}")
        return None

if __name__ == "__main__":
    # Replace with your actual connection string, container name, blob name, and file path
    connect_str = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
    container = "my-blob-container"
    blob = "my-uploaded-blob.txt"
    local_file = "path/to/your/local/file.txt"

    if not connect_str:
        print("Please set the AZURE_STORAGE_CONNECTION_STRING environment variable.")
    elif not os.path.exists(local_file):
        print(f"Error: File not found at '{local_file}'.")
    else:
        # Ensure container exists (optional, but good practice)
        try:
            blob_service_client = BlobServiceClient.from_connection_string(connect_str)
            blob_service_client.create_container(container)
            print(f"Container '{container}' is ready.")
        except Exception as e:
            # Ignore if container already exists
            if "ContainerAlreadyExists" not in str(e):
                print(f"Error creating or accessing container: {e}")
                # If container creation failed, don't proceed with upload
                exit()

        blob_url = upload_blob(connect_str, container, blob, local_file)
        if blob_url:
            print(f"Blob URL: {blob_url}")
                

Upload a Blob (Java)

This sample demonstrates how to upload a block blob to Azure Storage.


import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BlobUploadSample {

    public static void uploadBlob(String connectionString, String containerName, String blobName, String filePath) {
        try {
            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
                .connectionString(connectionString)
                .buildClient();

            // Get a client that will be used to interact with a specific blob
            BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);

            // Create container if it doesn't exist (optional)
            if (!containerClient.exists()) {
                containerClient.create();
                System.out.println("Container created: " + containerName);
            }

            BlobClient blobClient = containerClient.getBlobClient(blobName);
            File file = new File(filePath);
            FileInputStream fileStream = new FileInputStream(file);

            blobClient.upload(fileStream, file.length());
            System.out.println("Uploaded blob '" + blobName + "' to container '" + containerName + "' from file '" + filePath + "'.");

        } catch (FileNotFoundException e) {
            System.err.println("Error: File not found at " + filePath);
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Error uploading blob: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("An unexpected error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // Replace with your actual connection string, container name, blob name, and file path
        String connectionString = System.getenv("AZURE_STORAGE_CONNECTION_STRING");
        String containerName = "my-blob-container";
        String blobName = "my-uploaded-blob.txt";
        String filePath = "path/to/your/local/file.txt";

        if (connectionString == null || connectionString.isEmpty()) {
            System.err.println("Please set the AZURE_STORAGE_CONNECTION_STRING environment variable.");
            return;
        }

        if (!new File(filePath).exists()) {
            System.err.println("Error: File not found at '" + filePath + "'.");
            return;
        }

        uploadBlob(connectionString, containerName, blobName, filePath);
    }
}
                

Upload a Blob (JavaScript)

This sample demonstrates how to upload a block blob to Azure Storage using the Azure SDK for JavaScript.


const { BlobServiceClient } = require("@azure/storage-blob");

async function uploadBlob(connectionString, containerName, blobName, filePath) {
    const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
    const containerClient = blobServiceClient.getContainerClient(containerName);

    // Ensure container exists (optional)
    await containerClient.createIfNotExists();
    console.log(`Container '${containerName}' is ready.`);

    const blockBlobClient = containerClient.getBlockBlobClient(blobName);

    const fs = require('fs');
    const data = fs.readFileSync(filePath);

    try {
        await blockBlobClient.upload(data, data.length);
        console.log(`Uploaded blob '${blobName}' to container '${containerName}' from file '${filePath}'.`);
        return blockBlobClient.url;
    } catch (error) {
        console.error("Error uploading blob:", error);
        return null;
    }
}

async function main() {
    // Replace with your actual connection string, container name, blob name, and file path
    const connectionString = process.env.AZURE_STORAGE_CONNECTION_STRING;
    const containerName = "my-blob-container";
    const blobName = "my-uploaded-blob.txt";
    const filePath = "path/to/your/local/file.txt"; // Ensure this path is correct

    if (!connectionString) {
        console.error("Please set the AZURE_STORAGE_CONNECTION_STRING environment variable.");
        return;
    }

    const fs = require('fs');
    if (!fs.existsSync(filePath)) {
        console.error(`Error: File not found at '${filePath}'.`);
        return;
    }

    const blobUrl = await uploadBlob(connectionString, containerName, blobName, filePath);
    if (blobUrl) {
        console.log(`Blob URL: ${blobUrl}`);
    }
}

main().catch((err) => {
    console.error("An error occurred:", err);
});
                

Upload a Blob (Go)

This sample demonstrates how to upload a block blob to Azure Storage.


package main

import (
	"context"
	"fmt"
	"io"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
)

func uploadBlob(ctx context.Context, connectionString, containerName, blobName, filePath string) error {
	client, err := azblob.NewClientFromConnectionString(connectionString, nil)
	if err != nil {
		return fmt.Errorf("failed to create blob client: %w", err)
	}

	// Create container if it doesn't exist (optional)
	_, err = client.CreateContainer(ctx, containerName, nil)
	if err != nil {
		// Ignore if container already exists
		if !blob.HasConflictError(err) {
			return fmt.Errorf("failed to create container: %w", err)
		}
		fmt.Printf("Container '%s' already exists.\n", containerName)
	} else {
		fmt.Printf("Container '%s' created.\n", containerName)
	}

	file, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("failed to open file: %w", err)
	}
	defer file.Close()

	fileInfo, err := file.Stat()
	if err != nil {
		return fmt.Errorf("failed to get file info: %w", err)
	}
	fileSize := fileInfo.Size()

	_, err = client.UploadFile(ctx, containerName, blobName, file, &azblob.UploadFileOptions{
		ContentType: "application/octet-stream", // Or determine dynamically
		BlockSize:   4 * 1024 * 1024,           // 4MB block size
		MaxSize:     nil,                       // nil means unlimited
	})
	if err != nil {
		return fmt.Errorf("failed to upload file: %w", err)
	}

	fmt.Printf("Uploaded blob '%s' to container '%s' from file '%s'.\n", blobName, containerName, filePath)
	return nil
}

func main() {
	connectionString := os.Getenv("AZURE_STORAGE_CONNECTION_STRING")
	containerName := "my-blob-container"
	blobName := "my-uploaded-blob.txt"
	filePath := "path/to/your/local/file.txt" // Ensure this path is correct

	if connectionString == "" {
		fmt.Println("Please set the AZURE_STORAGE_CONNECTION_STRING environment variable.")
		return
	}

	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		fmt.Printf("Error: File not found at '%s'.\n", filePath)
		return
	}

	ctx := context.Background()
	err := uploadBlob(ctx, connectionString, containerName, blobName, filePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
	}
}

                

Upload a Blob (Azure CLI)

This sample demonstrates how to upload a block blob to Azure Storage using the Azure CLI.


#!/bin/bash

# --- Configuration ---
# Replace with your Azure Storage account name and key, or use `az login`
# If using `az login`, you can skip `account-name` and `account-key`
AZURE_STORAGE_ACCOUNT_NAME="yourstorageaccountname"
AZURE_STORAGE_ACCOUNT_KEY="yourstorageaccountkey" # Or fetch using `az storage account keys list`

CONTAINER_NAME="my-blob-container"
BLOB_NAME="my-uploaded-blob.txt"
LOCAL_FILE_PATH="path/to/your/local/file.txt" # Ensure this path is correct

# --- Script ---

# Check if Azure CLI is installed
if ! command -v az &> /dev_null
then
    echo "Azure CLI is not installed. Please install it first."
    exit 1
fi

# Check if the local file exists
if [ ! -f "$LOCAL_FILE_PATH" ]; then
    echo "Error: Local file not found at '$LOCAL_FILE_PATH'."
    exit 1
fi

echo "Attempting to upload blob '$BLOB_NAME' from '$LOCAL_FILE_PATH' to container '$CONTAINER_NAME'."

# Ensure container exists (optional, but good practice)
# Using `az storage container create` will create the container if it doesn't exist
echo "Ensuring container '$CONTAINER_NAME' exists..."
az storage container create \
  --account-name "$AZURE_STORAGE_ACCOUNT_NAME" \
  --account-key "$AZURE_STORAGE_ACCOUNT_KEY" \
  --name "$CONTAINER_NAME" \
  --public-access off \
  --fail-on-exist # Fail if it already exists to avoid accidental overwrites if not intended

if [ $? -ne 0 ]; then
    echo "Container creation failed. It might already exist or there was an authentication issue."
    # We can proceed if the container already exists, as the upload command will work.
    # If you want to strictly enforce creation, remove the --fail-on-exist or handle the error differently.
fi

# Upload the blob
echo "Uploading blob..."
az storage blob upload \
  --account-name "$AZURE_STORAGE_ACCOUNT_NAME" \
  --account-key "$AZURE_STORAGE_ACCOUNT_KEY" \
  --container-name "$CONTAINER_NAME" \
  --name "$BLOB_NAME" \
  --file "$LOCAL_FILE_PATH" \
  --output none # Suppress JSON output for cleaner logs

if [ $? -eq 0 ]; then
  echo "Successfully uploaded blob '$BLOB_NAME' to container '$CONTAINER_NAME'."
  echo "You can view the blob at:"
  echo "https://"$AZURE_STORAGE_ACCOUNT_NAME".blob.core.windows.net/"$CONTAINER_NAME"/"$BLOB_NAME
else
  echo "Error: Blob upload failed."
  exit 1
fi