You have a problem with your Save() method: you're not returning a Task, and so the calling method has no way to wait for it to finish. That would be fine if you just wanted to fire and forget it, but you can't do that because the stream you pass in is going to be disposed as soon as the Save()
method returns (thanks to the using
statement).
Instead, you're going to have to either return a Task
and await
in the calling method, or you're going to have to not have the file stream in a using
block, and instead let the Save()
method dispose of it when its finished.
One way you could re-write your code would be as follows:
(snippet of calling method):
var result = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
foreach (var item in result.Contents)
{
using (var fileStream = await item.ReadAsStreamAsync())
{
await fileStorageService.Save(@"large/Sam.jpg", fileStream);
}
item.Dispose();
}
And the Save method:
public async Task Save(string path, Stream source)
{
await CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"])
.CreateCloudBlobClient()
.GetContainerReference("images")
.GetBlockBlobReference(path)
.UploadFromStreamAsync(source);
}