How to use Azure Blob Storage on Android

I’ve been asked about this a few times so this is just a quick Azure Blob Storage tutorial using the Azure Android SDK.

Download the Azure Storage SDK

You can get the SDK from here:

https://github.com/azure/azure-storage-android

Setup your own blob storage

  • Log in to the Azure portal @ portal.azure.com
  • Click on the ‘New’ button in the top left corner -> ‘Data + Storage’ -> ‘Storage account’ -> ‘Create’

blob 1

  • Fill in the name of your storage, and set the other field to whatever is relevant to you and press ‘Create’

blob 2

  • Once it has finished building go to: ‘Blob’ -> ‘Container’ -> name your container, in my case I named it ‘dateface’ which is my apps name (a container is simply just a folder to store your files (a.k.a. ‘blobs’). And finally, make sure you set the ‘Access type’ to ‘Blob’. Then press ‘Create’.

blob 3

  • The connection key for your storage account can be found by clicking on the key icon

blob 4

Code

private static final String storageURL = "BLOB_STORAGE_URL";
private static final String storageContainer = "NAME_OF_BLOB_STORAGE_CONTAINER";
private static final String storageConnectionString = "BLOB_STORAGE_CONNECTION_STRING";

protected void storeImageInBlobStorage(String imgPath){
    try
    {
        // Retrieve storage account from connection-string.
        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.getContainerReference(storageContainer);

        // Create or overwrite the blob (with the name "example.jpeg") with contents from a local file.
        CloudBlockBlob blob = container.getBlockBlobReference("example.jpg");
        File source = new File(imgPath);
        blob.upload(new FileInputStream(source), source.length());
    }
    catch (Exception e)
    {
        // Output the stack trace.
        e.printStackTrace();
    }
}