Skip to content

Instantly share code, notes, and snippets.

@nickharris
Created November 13, 2012 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickharris/4063605 to your computer and use it in GitHub Desktop.
Save nickharris/4063605 to your computer and use it in GitHub Desktop.
var azure = require('azure');
var qs = require('querystring');
function insert(item, user, request) {
var accountName = '<replace with your storage account name>';
var accountKey = '<replace with your storage account key>';
var host = accountName + '.blob.core.windows.net';
var canonicalizedResource = '/' + item.containerName + '/' + item.resourceName;
//Must be lowercase
item.containerName = item.containerName.toLowerCase();
//Create the container if it does not exist
//we will use public read access for the blobs and will use a SAS to upload
var blobService = azure.createBlobService(accountName, accountKey, host);
blobService.createContainerIfNotExists(item.containerName, {publicAccessLevel : 'blob'}, function(error){
if(!error){
// Container exists now define a policy that provides write access
// that starts immediately and expires in 5 mins
var sharedAccessPolicy = {
AccessPolicy:{
Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.WRITE,
//Start: //use for start time in future, beware of server time skew
Expiry: formatDate(new Date(new Date().getTime() + 5 * 60 * 1000)) //5 minutes from now
}
};
//Generate the SAS for your BLOB
var sasQueryString = getSAS(accountName,
accountKey,
canonicalizedResource,
azure.Constants.BlobConstants.ResourceTypes.BLOB,
sharedAccessPolicy);
//full path for resource with sas
item.sas = 'https://' + host + canonicalizedResource + '?' + sasQueryString;
}
else{
console.error(error);
}
request.execute();
});
}
function getSAS(accountName, accountKey, path, resourceType, sharedAccessPolicy) {
return qs.encode(new azure.SharedAccessSignature(accountName, accountKey)
.generateSignedQueryString(path, {}, resourceType, sharedAccessPolicy));
}
function formatDate(date){
var raw = date.toJSON();
//blob service does not like milliseconds on the end of the time so strip
return raw.substr(0, raw.lastIndexOf('.')) + 'Z';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment