Related Content
Tags
Architecture
Integrations

Use Blob Storage to save files on Azure hosting

Posted by Joel Varty on February 9, 2012
0 people like this tutorial
Rate:

If you need to save files from your application and you are hosted in our Azure hosting environment, the most efficient way to do this is to use Blob storage.

You COULD use Amazon S3 to store these files, but then you would have to pay the transfer changes between your website and S3 every time you saved/retrieved the file.  With Blob storage, you don't pay if it's all within one Azure data center.

To start with, you'll need to get your own Azure Storage account, and download the Azure SDK.

The azure tools are located here. Installing them should be fairly quick and easy.

The account setup easy too, and if you belong to MSDN, it might even be included. Go here to find get started with that.

Once you have your Azure account, go to the management portal: https://windows.azure.com/ and create a new storage account.  Make sure you use the North Central UC region, as that's where your site is located.

Next, grab the account name and access key by selecting it in the portal and copying the values from the properties panel.

Put those values into your web.config appSettings section of you website.

Now, you need to add a reference to the Azure Storage assembly (Microsoft.WindowsAzure.StorageClient) to your website project in Visual Studio.

 

Finally, you are ready to write some code. 

Here is how to handle an upload:

string containerName = "mycontainer"//container must be lowercase, no special characters
			
StorageCredentialsAccountAndKey cred = new StorageCredentialsAccountAndKey(accountName, accountKey);
CloudStorageAccount storageAccount = new CloudStorageAccount(cred);
CloudBlobClient blobClient = storageAccount;
CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
blobContainer.CreateIfNotExist();
 
CloudBlob blob = blobContainer.GetBlobReference(filepath);
blob.Properties.ContentType = Request.Files[0].ContentType;
blob.UploadFromStream(Request.Files[0].InputStream);

Here is how to handle a download:

string containerName = "mycontainer"//container must be lowercase, no special characters
string filepath = "mypath/filename.ext"StorageCredentialsAccountAndKey cred = new StorageCredentialsAccountAndKey(accountName, accountKey);
CloudStorageAccount storageAccount = new CloudStorageAccount(cred);
CloudBlobClient blobClient = storageAccount;
 
//get a reference to the blob
CloudBlob blob = blobClient.GetBlobReference(string.Format("{0}/{1}", containerName, filepath));
 
//write the file to the http response
blob.DownloadToStream(Response.OutputStream);

Now, we probably want to add ouput caching and client cache detection on top of this, but that's fairly simple to do.  Here is a more complete download example...

blob.FetchAttributes();  //careful - this will error if the blob does not exist.
 
//check the if modified since header from the browser...
DateTime dtIfModifiedSince = DateTime.MinValue;
if (DateTime.TryParse(Request.Headers["If-Modified-Since"], out dtIfModifiedSince)
	&& (blob.Properties.LastModifiedUtc - dtIfModifiedSince.ToUniversalTime()).TotalSeconds < 1.0)
{
	//not changed...
	Response.StatusCode = 304;
	return;
}
 
//set the last mod
Response.Cache.SetLastModified(blob.Properties.LastModifiedUtc);
 
//pull the content encoding if it was set...
if (!string.IsNullOrWhiteSpace(blob.Properties.ContentEncoding))
{
	Response.AppendHeader("Content-Encoding", blob.Properties.ContentEncoding);
}
 
//set the cache control
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
Response.Cache.SetMaxAge(TimeSpan.FromSeconds(300));
Response.Expires = 300;

//set the output content type
Response.ContentType = blob.Properties.ContentType;
 
//download the asset to the output stream
blob.DownloadToStream(Response.OutputStream);

 

 

Add a Comment

   
  
 
 
   
Submit

LOGIN

Log in with your Agility username and password or
register for the site




Log In

REGISTER












Register

FORGOT PASSWORD