3

I have a method to upload my image to Azure blob storage. I have my account already created, and a name and key placed in my app. The behavior I'm seeing is that await UploadFromByteArrayAsync(...) returns and my method returns a URL. However, when I navigate to my azure blob storage in Microsoft Azure Storage Explorer, I can see that no blob has been created. Obviously, navigating to the URL returned by the method returns 404 also. The method has successfully created my container, so there is a definite connection with appropriate perms to my storage account, I have checked the content of the byte array and it contains actual data. Does anyone know why my image is never uploaded?

public async Task<string> UploadImage(byte[] imageByteArr)
{
    // Retrieve storage account from the connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=redacted;AccountKey=redacted;EndpointSuffix=core.windows.net");

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference("user-images");

    // Create the container if it doesn't already exist.
    await container.CreateIfNotExistsAsync().ConfigureAwait(false);

    var docId = Guid.NewGuid().ToString();
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(docId);

    await blockBlob.UploadFromByteArrayAsync(imageByteArr, 0, imageByteArr.Length);

    blockBlob.Properties.ContentType = "image/jpg";
    await blockBlob.SetPropertiesAsync();

    return blockBlob.Uri.ToString();
}
gorkem
  • 731
  • 1
  • 10
  • 17
ElFik
  • 897
  • 2
  • 13
  • 31
  • 1
    I'm curious to know how you're calling this `UploadImage` method? Are you awaiting to get this finish executing? – Gaurav Mantri May 14 '17 at 13:30
  • seems to be a problem with 'await'ing on the call to UploadImage. Try calling the 'Result' property on the returned value of UploadImage. For a more detailed explanation on how to call an async method you can check this reply - http://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c – alwayslearning May 14 '17 at 14:38
  • 1
    Can you insert a blockBlob.ExistsAsync() call after the upload to see if it exists or not? You might just not have permissions in the browser to see the url. – JLaanstra May 14 '17 at 19:17

1 Answers1

3

I had missed a step in the creation of the blobs tutorial I was following. We need to call the following when creating the container in the codebehind so that we have public access to the image uploaded.

container.SetPermissions(
    new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
ElFik
  • 897
  • 2
  • 13
  • 31