Azure Blob Storage is part of the Microsoft Azure Storage service, providing a relatively low cost service for storing large amounts of unstructured data, such as text or blobs; “blobs” stands for Binary Large Objects. A blob is a collection of binary data stored as a single entity. It typically comprises images, audio, or any other file.

In this tutorial, we will describe the process of creating a Web API project and uploading a file directly to a container in your Azure Storage account.

Create a storage account in Microsoft Azure

From Preview Portal, select New > Data and Storage > Storage Account

azure-storage-service-new-account

Enter the name, the resource group and the location of your storage account.

azure-storage-service-new-account-details

After a few minutes your storage account will be ready to use!

Create a container to store your files

In order to store your files in Azure Blob Storage, you need to have a container, which groups any set of blobs. A container may have two different access types:

  • Private, which does not provide anonymous access to the container or the blobs therein.
  • Public, in which case all the blobs within the container can be accessed publicly through anonymous access; however, in order to list all blobs in a container, the account credentials are necessary.

Let’s name the container in our example “images” and set its access type to Public.

azure-storage-service-new-container

[box type=”info” width=”100%” ]There is no limitation as to the number of containers per account nor as to the number of blobs per container.[/box]

Storage Account Credentials

In order to have access to the container and upload your files, you are going to need:

  • Storage Account Name and Access Key, or
  • Connection String

both provided from Settings > Access Keys.

azure-storage-service-new-access-keys

 

Create a project in Visual Studio

For starters, you need to create a New ASP.NET project in Visual Studio, selecting Web API from ASP.NET 4.6 Templates and leaving Authentication to “No Authentication”.

Install Windows Azure Storage Nuget package

Then, search for “azure storage” in Nuget Gallery

windows-azure-storage-nuget-package

or type the command below from Package Manager Console:

Install-Package WindowsAzure.Storage

Add Azure Storage Credentials

Subsequently, add your storage account credentials in the AppSettings section of your Web.config:

<appSettings>
 <add key="storage:account:name" value="{account_name}"/>
 <add key="storage:account:key" value="{account_key}"/>
</appSettings>

Create a Custom Stream Provider

Afterwards, you need to extend MultipartFormDataStreamProvider class by creating your own AzureStorageMultipartFormDataStreamProvider, which will be responsible for writing streamed data directly to a blob in your container.

public class AzureStorageMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    private readonly CloudBlobContainer _blobContainer;
    private readonly string[] _supportedMimeTypes = { "image/png", "image/jpeg", "image/jpg" };

    public AzureStorageMultipartFormDataStreamProvider(CloudBlobContainer blobContainer) : base("azure")
    {
        _blobContainer = blobContainer;
    }

    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
    {
        if (parent == null) throw new ArgumentNullException(nameof(parent));
        if (headers == null) throw new ArgumentNullException(nameof(headers));

        if (!_supportedMimeTypes.Contains(headers.ContentType.ToString().ToLower()))
        {
            throw new NotSupportedException("Only jpeg and png are supported");
        }

        // Generate a new filename for every new blob
        var fileName = Guid.NewGuid().ToString();

        CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(fileName);

        if (headers.ContentType != null)
        {
            // Set appropriate content type for your uploaded file
            blob.Properties.ContentType = headers.ContentType.MediaType;
        }

        this.FileData.Add(new MultipartFileData(headers, blob.Name));

        return blob.OpenWrite();
    }
}

Create an Upload Api Controller

Finally, you need to create an Api Controller, which will provide the API for the file to be uploaded in your storage account.

[RoutePrefix("api/upload")]
public class UploadController : ApiController
{
    private const string Container = "images";

    [HttpPost, Route("")]
    public async Task<IHttpActionResult> UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var accountName = ConfigurationManager.AppSettings["storage:account:name"];
        var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
        var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer imagesContainer = blobClient.GetContainerReference(Container);
        var provider = new AzureStorageMultipartFormDataStreamProvider(imagesContainer);

        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);
        }
        catch (Exception ex)
        {
            return BadRequest($"An error has occured. Details: {ex.Message}");
        }

        // Retrieve the filename of the file you have uploaded
        var filename = provider.FileData.FirstOrDefault()?.LocalFileName;
        if (string.IsNullOrEmpty(filename))
        {
            return BadRequest("An error has occured while uploading your file. Please try again.");
        }

        return Ok($"File: {filename} has successfully uploaded");
    }
}

Testing Request with Postman

You can create a simple Post Request through Postman, to test how the above works.

post-man-upload-success

View your files in Azure Blob Storage

All successfully uploaded images will be available in “images” container, in Azure Preview Portal.

2016-02-06_17h49_08

You can download the source code from here.

 

Categorized in:

Tagged in:

,