Code Examples for Azure Blob Storage
Explore a variety of code snippets and complete examples demonstrating how to interact with Azure Blob Storage using different SDKs and languages. These examples cover common scenarios and best practices.
Creating and Uploading Blobs
Learn how to create a blob container and upload various types of data (block blobs, append blobs, page blobs) to Azure Blob Storage.
Upload a Block Blob (Python SDK)
Python
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
container_name = "my-container"
blob_name = "my-blob.txt"
local_file_path = "path/to/your/local/file.txt"
# Create the BlobServiceClient object
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
# Get a client to interact with a specific blob
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
print(f"Uploading to blob: {blob_name}")
with open(local_file_path, "rb") as data:
blob_client.upload_blob(data, overwrite=True)
print("Blob uploaded successfully.")
View Full Python Example
Upload a Block Blob (Node.js SDK)
JavaScript
const { BlobServiceClient } = require("@azure/storage-blob");
const connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
const containerName = "my-container";
const blobName = "my-blob.txt";
const localFilePath = "./path/to/your/local/file.txt"; // Use relative or absolute path
async function uploadBlob() {
const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
const containerClient = blobServiceClient.getContainerClient(containerName);
console.log(`Uploading to blob: ${blobName}`);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadResponse = await blockBlobClient.uploadFile(localFilePath);
console.log(`Upload successful: ${uploadResponse.requestId}`);
}
uploadBlob().catch(err => console.error(err.message));
View Full Node.js Example
Downloading and Retrieving Blobs
Understand how to download blob content, list blobs within a container, and retrieve blob metadata.
Download a Blob (Java SDK)
Java
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class DownloadBlob {
public static void main(String[] args) throws Exception {
String connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
String containerName = "my-container";
String blobName = "my-blob.txt";
String downloadFilePath = "path/to/save/downloaded/file.txt";
// Create a BlobServiceClient
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
.connectionString(connectionString)
.buildClient();
// Get a client to interact with a specific blob
BlobClient blobClient = blobServiceClient.getBlobContainerClient(containerName).getBlobClient(blobName);
System.out.println("Downloading blob: " + blobName);
try (OutputStream stream = Files.newOutputStream(Paths.get(downloadFilePath))) {
blobClient.downloadStream(stream);
System.out.println("Blob downloaded successfully to: " + downloadFilePath);
}
}
}
View Full Java Example
Managing Containers and Blob Properties
Discover how to manage blob containers, set access policies, manage blob metadata, and handle versioning.
List Blobs in a Container (Azure CLI)
CLI
az storage blob list --account-name --account-key --container-name my-container --output table
Learn More about CLI Commands
Advanced Features
Examples for advanced scenarios like using SAS tokens, server-side encryption, immutability policies, and blob snapshots.
Generate SAS Token (C# SDK)
C#
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
using System;
public class GenerateSasToken
{
public static void Main(string[] args)
{
string connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
string containerName = "my-container";
string blobName = "my-blob.txt";
var blobServiceClient = new BlobServiceClient(connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = containerClient.GetBlobClient(blobName);
// Define the SAS token parameters
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerName,
BlobName = blobName,
Resource = "b", // 'b' for blob
ExpiresOn = DateTimeOffset.UtcNow.AddHours(1), // Token expires in 1 hour
Protocol = SasProtocol.Https // Use HTTPS
};
// Set the permissions (read, write, delete, list, create)
sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);
// Get the SAS token string
string sasToken = sasBuilder.ToSasQueryParameters(new Azure.Storage.StorageSharedKeyCredential(
blobServiceClient.AccountName,
"" // Fetch account key securely
)).Encode();
Console.WriteLine($"Generated SAS Token: {sasToken}");
Console.WriteLine($"Full URI: {blobClient.Uri}/?{sasToken}");
}
}
View Full C# Example