In this post I’m going to bring together a couple of my previous posts that discuss retrieving and saving images, and retrieving a Shared Access Signature from a controller which will allow me to write to a particular container within Blob Storage. To complete the implementation I’ll use the Windows Azure Storage library from NuGet – it only installs for Windows platforms as there’s no PCKL or Xamarin support for this library currently.
As the Windows Azure Storage library is current platform specific, I’ll need to wrap it in a simple interface that makes it easy for me to write data to Blob Storage – I’ll come back to that. For the time being I’m just going to retrieve the SAS and use it along with the storage library to upload an image. So I’ll start by invoking the sharedaccesssignature controller using the GET verb as I want to ensure the container is created if it doesn’t already exist. This will return a SAS which I can use in the upload process.
public async Task<string> RetrieveSharedAccessSignature()
{
var sas = await MobileService.InvokeApiAsync<string>(“sharedaccesssignature”, HttpMethod.Get,
new Dictionary<string, string> { { “id”, “test” } });
return sas;
}
Next I want to capture an image, in this case picking a photo, and uploading it to a specified blobg.
private async void CaptureClick(object sender, RoutedEventArgs e)
{
var picker = new MediaPicker();
var sas = string.Empty;
using (var media = await picker.PickPhotoAsync())
using (var strm = media.GetStream())
{
sas = await CurrentViewModel.RetrieveSharedAccessSignature();Debug.WriteLine(sas);
// Get the URI generated that contains the SAS
// and extract the storage credentials.
var cred = new StorageCredentials(sas);
var imageUri = new Uri(“https://realestateinspector.blob.core.windows.net/test/testimage.png”);// Instantiate a Blob store container based on the info in the returned item.
var container = new CloudBlobContainer(
new Uri(string.Format(“https://{0}/{1}”,
imageUri.Host, “test”)), cred);// Upload the new image as a BLOB from the stream.
var blobFromSASCredential = container.GetBlockBlobReference(“testimage.png”);
await blobFromSASCredential.UploadFromStreamAsync(strm.AsInputStream());
}}
Clearly this code isn’t well factored but it’s here as a quick example of how you can use a SAS to upload content to blob storage.