I am trying to upload an image to azure blob storage. However when I look at the end result on azure and it just creates an empty file.
[HttpPost("Import")]
public IActionResult Import(IFormFile filepond)
{
const string accountName = "accountName";
const string key = "key14881851";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExistsAsync();
container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blob = container.GetAppendBlobReference("test.jpg");
blob.UploadFromStreamAsync(filepond.OpenReadStream());
return Ok();
}
Some questions (other than why I am getting an empty file).
From the left menu, select Storage accounts, then select the name of your storage account. Select Containers, then select the thumbnails container. Select Upload to open the Upload blob pane. Choose a file with the file picker and select Upload.
Azure Blob Storage is Microsoft's massively scalable object storage solution for the cloud. Blob Storage is designed for storing images and documents, streaming media files, managing backup and archive data, and much more.
...do I need to await them for everything to work properly(ie if the container does not exist that it gets created before a file is written to the container)
Yes. Async methods return a task and you have to wait until this task is completed. That's why your file is emty.
Do I need to wrap the UploadFromStreamAsync in a using statement.
I would call it cleaner, while I'n not sure if it absolutely necessary here.
I would write it like so (not tested):
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
await container.CreateIfNotExistsAsync();
container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blob = container.GetBlockBlobReference("test.jpg");
using(var stream = filepond.OpenReadStream()) {
await blob.UploadFromStreamAsync(stream);
}
Please note, that I replaced GetAppendBlobReference() with GetBlockBlobReference().
Docs with examples https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet?tabs=windows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With