Upload blobs using UploadFromStream to Azure Storage and using ResponseReceivedEventArgs to track the upload progress
While uploading a stream of various sizes using UploadFromStream, and using ResponseReceivedEventArgs to track the HTTPStatusCode you will see the following behavior:
1) For a blob whose size less than(or equal to)32 MB, the lib will send it in one piece
2) For a blob whose size is bigger than 32 MB, the lib will chuck it into blocks(Max size is 4MB) to send.
After spending some time I was able to get ResponseReceivedEventArgs to track how much data have been uploaded. The code snippet is as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Diagnostics;
using System.Data.Services.Common;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string accountSettings = "";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(accountSettings);
CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("test");
container.CreateIfNotExist();
string blobName = "testBlob";
var blob = container.GetBlockBlobReference(blobName);
MemoryStream randomDataForPut = RandomData(33*1024*1024);
long totalBytes = 0;
blobStorage.ResponseReceived += new EventHandler<ResponseReceivedEventArgs>((obj, responseReceivedEventArgs)
=>
{
if (responseReceivedEventArgs.RequestUri.ToString().Contains("comp=block&blockid"))
{
totalBytes += Int64.Parse(responseReceivedEventArgs.RequestHeaders["Content-Length"]);
}
});
blob.UploadFromStream(randomDataForPut);
}
catch (Exception e)
{
System.Diagnostics.Trace.TraceError(e.ToString());
}
}
public static MemoryStream RandomData(long length)
{
var result = new MemoryStream();
Random r = new Random();
for (long i = 0; i < length; i++)
result.WriteByte((byte)(r.Next(256)));
result.Position = 0;
return result;
}
}
}