2
votes

I would like to asynchronously upload a single file via an ASP.NET Forms C# project to Azure Blob storage and then delete the file from the local storage once the upload is completed. The files will be large hence why I don't want to leave the user waiting for the operation to complete.

My code seems to work but I'm wondering if there is a better or best practise way of achieving this?

public async Task<string> SaveImageToBLOBStorageAndDelFromWebSpace(ImageDetails objImageDetail)
{

var container = _client.GetContainerReference(objImageDetail.BlobContainer);

var blob = container.GetBlockBlobReference(objImageDetail.FileName);

await blob.UploadFromFileAsync(HttpContext.Current.Server.MapPath(objImageDetail.FullPathIncFileName)).ConfigureAwait(false);

try
{
            File.Delete(System.Web.Hosting.HostingEnvironment.MapPath(objImageDetail.FullPathIncFileName));

}
catch (Exception e)
{
throw;
}
    return objImageDetail.FileName;
}
1

1 Answers

0
votes

As BlobRequestOptions.ParallelOperationThread states as follows:

Gets or sets the number of blocks that may be simultaneously uploaded.

Remarks:

When using the UploadFrom* methods on a blob, the blob will be broken up into blocks. Setting this value limits the number of outstanding I/O "put block" requests that the library will have in-flight at a given time. Default is 1 (no parallelism). Setting this value higher may result in faster blob uploads, depending on the network between the client and the Azure Storage service. If blobs are small (less than 256 MB), keeping this value equal to 1 is advised.

I assumed that you could explicitly set the ParallelOperationThreadCound for faster blob uploading:

var requestOption = new BlobRequestOptions()
{
    ParallelOperationThreadCount = 5 //Gets or sets the number of blocks that may be simultaneously uploaded.
};

//upload a blob from the local file system
await blockBlob.UploadFromFileAsync("{your-file-path}",null,requestOption,null);

Also, you could use WindowsAzure.Storage.DataMovement.TransferManager to upload the blob and track the upload progress.

// Setup the number of the concurrent operations
TransferManager.Configurations.ParallelOperations = 64;
// Setup the transfer context and track the upoload progress
SingleTransferContext context = new SingleTransferContext();
context.ProgressHandler = new Progress<TransferStatus>((progress) =>
{
    Console.WriteLine("Bytes uploaded: {0}", progress.BytesTransferred);
});
// Upload a local blob
var task = TransferManager.UploadAsync(
    sourcePath, destBlob, null, context, CancellationToken.None);
task.Wait();

For more details about Azure Storage Data Movement, you could refer to this article.