Using Windows Azure Blobs with Webscript

Today we published a new module and new example demonstrating how Webscript can be used to work with Windows Azure blob storage.

Windows Azure uses an HTTP-based API and supports two forms of authentication: a cryptographic signature in the Authorization header or a signature in the URL itself (as a query string parameter). This second form of authentication is called a Shared Access Signature. It's most commonly used to grant someone temporary access to a blob. This is especially popular among mobile app developers, who want to push files (such as photos) directly to blob storage. A Shared Access Signature (SAS) URL lets them do that.

In this example, we use Shared Access Signatures for both upload and download. After receiving an uploaded file from the browser, we generate a random blob name and then generate a SAS URL that allows us to write to it. Using that URL, we upload the file with a simple PUT request. Once that's done, we create a SAS URL that allows read-only permissions, and we give that URL back to the user so they can download the file again.

Here's the complete script, also available on the examples page:

local ACCOUNT='<AZURE STORAGE ACCOUNT>'
local KEY='<AZURE STORAGE KEY>'
local azure = require 'azure'
local container = 'demo'
local blobname = 'file_' .. math.random(99999999)
local duration = 300 -- five minutes
local writeurl = azure.blob.sas(ACCOUNT, KEY, container,
        blobname, 'w', duration) -- 'w' for write permissions
local file = request.files.file
http.request {
        method = 'put',
        url = writeurl,
        data = file.content,
        headers = { ['Content-Type'] = file.type }
}
local readurl = azure.blob.sas(ACCOUNT, KEY, container,
        blobname, 'r', duration) -- 'r' for read permissions
return '<a href="'..readurl..'">download file</a>',
        { ['Content-Type'] = 'text/html' }

Note that we also have a similar example for Amazon S3.