How to upload any file to Azure Blob storage service?
Microsoft Azure offers different types of storage like blob (binary large object), files, tables (key/value based), queues. In this post, I’ll tell you how to upload any file to Azure Blog storage service.
An application may need to upload any file like images, video, etc. Azure’s blob storage is the right storage solution that should be used for this purpose. The main focus of this post is blob storage and the front-end framework can be of your choice like ASP.NET MVC, Angular 2, AngularJS or some other framework.
Application
The project code used in this post is located on GitHub, so feel free to use it for learning purpose. I’ll be using ASP.NET MVC framework for this post. If you are using something else, even then this post can help you to learn about Azure’s blob storage. This application allows a user to upload an image as blob and show it back to the user. Similarly, any type of file can be saved using the same concept.
Azure’s Storage Account
To work with blob storage, an Azure account is required which is free for 30 days. If you already have an storage account, then you are good to follow next steps in the post. If not, please create this account by using the azure portal by going through New > Storage > Storage account - blob, file, table, queue. Fill up all the required information in the setup blade and click create which will just take few seconds to create an account.
Container
To use Azure’s blob storage service to upload any file as blob, we need to create what is called as a Container. Think about container as a folder that will store blob(s). A container cannot be nested inside another container like folders in file-system. To create a container, go to the storage account in portal, click Blob service and plus icon for container. A container needs to have a name (all lower-case) and an access type. The access type is the protection level:
- Private (hidden from anonymous user)
- Blob (to show blob to anonymous user)
- Container (to show all the blobs in container to anonymous user)
Uploading a blob from portal UI is quite easy. Click on the container and then click on upload that opens another blade to select a file from the file-system. The blob type can also be set as per the requirement:
- Block (like files on file-system, example: image, xml, movie files, etc. This is optimised for streaming)
- Page (used to store VHD files for virtual machines, optimised for reading, writing in the middle of the blob)
- Append (optimised to update the blob at the end, used for logging)
Next, create a container named `images` and set the access type to `Blob`.
Access Azure Blob Service from front-end application
As such I’m using ASP.NET MVC for front-end, like most of the Azure services, to consume this blob service we need a client package from Nuget Package Manager in the project named as `WindowsAzure.Storage` and the package version that is used for this post is 8.2.0. The client allows to connect to all types of storages in Azure like blob, table, file and queues. For blob storage, we will be using CloudBlobClient class.
Image Storage Service
Next, I’ve created a class named `ImageStorageService` that encapsulates usage of `CloudBlobClient` class instance. The controller of my application doesn’t need to use the client directly.
Let’s look at the implementation of this service:
public class ImageStorageService
{
private readonly CloudBlobClient _cloudBlobClient;
private readonly Uri _blobServiceEndpoint = new Uri(ConfigurationManager.AppSettings.Get("blobServiceEndpoint"));
public ImageStorageService()
{
var credentials = new StorageCredentials("storage account name", "enter your storage account access key here or get from web.config");
_cloudBlobClient = new CloudBlobClient(_blobServiceEndpoint, credentials);
}
public Uri GetResourceUri(string resourceId)
{
return new Uri(_blobServiceEndpoint, $"/images/{resourceId}");
}
public async Task<string> SaveImage(Stream imageInputStream)
{
string id = Guid.NewGuid().ToString();
CloudBlobContainer container = _cloudBlobClient.GetContainerReference("images");
CloudBlockBlob blob = container.GetBlockBlobReference(id);
await blob.UploadFromStreamAsync(imageInputStream);
return id;
}
}
Azure blob service can be accessed via an endpoint (HTTP request) and the reading, writing a blob to the container needs authentication key. Both of these information can be copied from the container and storage account’s access key respectively.
The service is quite easy as it uses the `CloudBlobClient` class instance to upload the image stream. The method named GetBlockBlobReference basically tries to get a reference to a blob by a new id, so as such this blob doesn’t exist, a new blob is created. Next, the stream is then uploaded and the newly generate id is then given back to the controller in order to show the image.
To show the image to anonymous user, the access type of the container was set to `Blob` and method named `GetResourceUri` is used to get exact Uri of image resource combining the service endpoint, container name and image resource reference.
Controller
Just for information, I’ll write the controller code below that takes care of uploading the image via custom image service and then showing the image to the user:
public class ImagesController : Controller
{
private ImageStorageService _imageStoreService;
public ImagesController()
{
_imageStoreService = new ImageStorageService();
}
public ActionResult Index()
{
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> Upload(HttpPostedFileBase image)
{
if (image != null)
{
string imageId = await _imageStoreService.SaveImage(image.InputStream);
return RedirectToAction("ShowImage", new {id = imageId});
}
return View("Index");
}
public ActionResult ShowImage(string id)
{
Uri imageUri = _imageStoreService.GetResourceUri(id);
return View(imageUri);
}
}
Use this link to access the source code of this application. I hope this post easily explains how to upload any file to Azure Blob storage service. For any issues, please use my repository or comment here. Please subscribe to my website to get more update for similar posts.
