public async Task <string> UploadAsync(FileType fileType, UploadFileProperties uploadFileProperties, Stream streamToUpload) { var blobClient = cloudStorageAccount.CreateCloudBlobClient(); var containerReference = blobClient.GetContainerReference(fileType.ToString().ToLower()); var blobName = GetBlobName(uploadFileProperties.FileName); var blobReference = containerReference.GetBlockBlobReference(blobName); blobReference.Metadata.Add(FileNameMetadata, uploadFileProperties.FileName); blobReference.Properties.ContentType = uploadFileProperties.ContentType; blobReference.Properties.ContentDisposition = uploadFileProperties.ContentDisposition; Func <Task <string> > uploadDelegate = async() => { await blobReference.UploadFromStreamAsync(streamToUpload); Log.Information($"{blobName} was uploaded to storage"); return(blobName); }; try { // try to upload file assuming container exists return(await uploadDelegate()); } catch (StorageException e) { // case when container was not created yet if (e.RequestInformation.HttpStatusCode == 404) { Log.Warning(e, "Exception while uploading file"); await EnsureContainerExists(containerReference); return(await uploadDelegate()); } Log.Error(e, "Failed to upload a file to storage"); throw; } }
public async Task <FileStorageWriteStream> GetWriteStreamAsync(FileType fileType, UploadFileProperties uploadFileProperties) { var blobClient = cloudStorageAccount.CreateCloudBlobClient(); var containerReference = blobClient.GetContainerReference(fileType.ToString().ToLower()); var blobName = GetBlobName(uploadFileProperties.FileName); var blobReference = containerReference.GetBlockBlobReference(blobName); blobReference.Metadata.Add(FileNameMetadata, uploadFileProperties.FileName); blobReference.Properties.ContentType = uploadFileProperties.ContentType; blobReference.Properties.ContentDisposition = uploadFileProperties.ContentDisposition; Func <Task <FileStorageWriteStream> > openStreamDelegate = async() => { var stream = await blobReference.OpenWriteAsync(); Log.Information($"Write stream to storage was opened for {blobName}"); return(new FileStorageWriteStream { Id = blobName, Stream = stream }); }; try { // try to open stream assuming container exists return(await openStreamDelegate()); } catch (StorageException e) { // case when container was not created yet if (e.RequestInformation.HttpStatusCode == 404) { Log.Warning(e, "Exception while opening a write stream to storage"); await EnsureContainerExists(containerReference); return(await openStreamDelegate()); } Log.Error(e, "Failed to open a write stream to storage"); throw; } }