In this sample, we will demonstrate common scenarios for Azure Blob Storage that includes creating, listing and deleting containers and blobs.
Azure Blob storage is a service for storing large amounts of unstructured object data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.
Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. The "Allowed origins" could be set to "*" to allow all the origins in this sample. For more information about CORS, see Cross-Origin Resource Sharing (CORS).
Importing azure-storage.blob.js
in your HTML file for blob operations.
<script src="azure-storage.blob.js"></script>
The BlobService
object lets you work with containers and blobs.
Following code creates a BlobService
object with storage account and SAS Token.
var blobUri = 'https://' + 'STORAGE_ACCOUNT' + '.blob.core.windows.net'; var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, 'SAS_TOKEN');
You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable AzureStorage.Blob
will be set, which is the start point where we can create service objects for blob and access to the storage utilities.
AzureStorage.Blob
is just like the object require('azure-storage')
returns in Node.js, but limits to Blob related interfaces.
Go to BlobService to view possible methods provided by BlobService
class.
BlobService
based on Storage Account Key for authentication besides SAS Token.
However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy.
A container provides a grouping of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs. Note that the container name must be lowercase.
BlobService
object provides plenty of interfaces for container operations.
BlobService
provides listContainersSegmented
and listContainersSegmentedWithPrefix
for retrieving the containers list under a storage account.
blobService.listContainersSegmented(null, function (error, results) { if (error) { // List container error } else { for (var i = 0, container; container = results.entries[i]; i++) { // Deal with container object } } });
BlobService
provides createContainer
and createContainerIfNotExists
for creating a container under a storage account.
blobService.createContainerIfNotExists('mycontainer', function(error, result) { if (error) { // Create container error } else { // Create container successfully } });
BlobService
provides deleteContainer
and deleteContainerIfExists
for deleting a container under a storage account.
blobService.deleteContainerIfExists('mycontainer', function(error, result) { if (error) { // Delete container error } else { // Delete container successfully } });
The sample will try to create an Azure Storage blob service object based on SAS Token authorization. Enter your Azure Storage account name and SAS Token here, and executable examples in following steps dependent on the settings here. Make sure you have set the CORS rules for the Azure Storage blob service, and the SAS Token is in valid period.
In the following executable example, you can try to list all the containers under your storage account settings, and try to create or delete one container from your account.
Click button to view the container list under your Azure Storage account
Click button to create a container under your Azure Storage account:
Click "Delete" button in the container list to delete the container under your Azure Storage account
Click "Select" button to select and operate with the blobs in next step
Blob: A file of any type and size. Azure Storage offers three types of blobs: block blobs, page blobs, and append blobs.
Block blobs are ideal for storing text or binary files, such as documents and media files. Append blobs are similar to block blobs in that they are made up of blocks, but they are optimized for append operations, so they are useful for logging scenarios. A single block blob can contain up to 50,000 blocks of up to 100 MB each, for a total size of slightly more than 4.75 TB (100 MB X 50,000). A single append blob can contain up to 50,000 blocks of up to 4 MB each, for a total size of slightly more than 195 GB (4 MB X 50,000).
Page blobs can be up to 1 TB in size, and are more efficient for frequent read/write operations. Azure Virtual Machines use page blobs as OS and data disks.
For details about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.
BlobService
provides listBlobsSegmented
and listBlobsSegmentedWithPrefix
for retrieving the blobs list under a container.
blobService.listBlobsSegmented('mycontainer', null, function (error, results) { if (error) { // List blobs error } else { for (var i = 0, blob; blob = results.entries[i]; i++) { // Deal with blob object } } });
BlobService
provides createBlockBlobFromBrowserFile
, createPageBlobFromBrowserFile
, createAppendBlobFromBrowserFile
and appendFromBrowserFile
for uploading or appending a blob from an HTML file in browsers.
Uploading blob from stream. You can set up the blob name as well as the size of this uploading session.
// If one file has been selected in the HTML file input element var file = document.getElementById('fileinput').files[0]; var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512; blobService.singleBlobPutThresholdInBytes = customBlockSize; var finishedOrError = false; var speedSummary = blobService.createBlockBlobFromBrowserFile('mycontainer', file.name, file, {blockSize : customBlockSize}, function(error, result, response) { finishedOrError = true; if (error) { // Upload blob failed } else { // Upload successfully } }); refreshProgress();
Checking the upload progress with speedSummary
object.
speedSummary.on('progress', function () { var process = speedSummary.getCompletePercent(); displayProcess(process); });
speedSummary.getCompletePercent()
only updates progress when a block is uploaded to server. There are 2 default settings that may influence the upload progress display.
blobService.singleBlobPutThresholdInBytes
is the maximum size (default 32MB), in bytes, of a blob before it must be separated into blocks.{blockSize: SizeInBytes}
of blobService.createBlockBlobFromStream()
is the size (default 4MB) of every block in the storage layer.
BlobService
provides interfaces for downloading a blob into browser memory.
Because of browser's sandbox limitation, we cannot save the downloaded data trunks into disk until we get all the data trunks of a blob into browser memory.
The browser's memory size is also limited especially for downloading huge blobs, so it's recommended to download a blob in browser with SAS Token authorized link directly.
Shared access signatures (SAS) are a secure way to provide granular access to blobs and containers without providing your storage account name or keys. Shared access signatures are often used to provide limited access to your data, such as allowing a mobile app to access blobs. The following code example generates a new shared access policy that allows the shared access signatures holder to perform read operations on the myblob blob, and expires 100 minutes after the time it is created.
var downloadLink = blobService.getUrl('mycontainer', 'myblob', 'SAS_TOKEN');
BlobService
provides deleteContainer
and deleteContainerIfExists
for deleting a blob under a storage account.
blobService.deleteBlobIfExists(container, blob, function(error, result) { if (error) { // Delete blob failed } else { // Delete blob successfully } });
After clicked the "Select" button on the container list in last step, you are able to operate with the blobs under the selected container.
Click button to view the blobs under your selected container
Click button to upload a local file to current container after selecting a file:
Click "Delete" button to delete the blob
Click "Download" link to download a blob to local
You can view the source code of this sample for detailed reference.