Valentyn
Valentyn

Reputation: 25

Save images from client in Azure storage

I have the following code. It is not giving me any errors, but I do not have an image in my folder in Azure storage.

            var bytes = person.Image.GetBytes();
        MemoryStream ms = new MemoryStream(bytes.Result);
  var storageCredentials = new StorageCredentials("AccountName", "***/pEYRskVHuAtUhcvLT/Ct*****/71lLMUCgTybnm****B4WO/AGFe****==");
        var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
        var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

        var container = cloudBlobClient.GetContainerReference("https://*********.blob.core.windows.net/images");

        var newBlob = container.GetBlockBlobReference("myfile.jpg");
        newBlob.UploadFromStreamAsync(ms);

What should I do here? I have empty image in store?

private async Task UploadFile(string path,Stream stream)
        {

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=f********ge1;AccountKey=w9S**************==;EndpointSuffix=core.windows.net");

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference("images");

        // Retrieve reference to a blob named "myblob".
        CloudBlockBlob blockBlob = container.GetBlockBlobReference("img.jpg");
        blockBlob.Properties.ContentType = "image/jpeg";

        // Create or overwrite the "myblob" blob with contents from a local file.
        using (var fileStream = stream)
        {
            await blockBlob.UploadFromStreamAsync(fileStream);
        }

    }

Upvotes: 1

Views: 99

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136334

Most likely you're running into this issue is because you're calling an async operation and not waiting for it to complete:

newBlob.UploadFromStreamAsync(ms);

You could fix this by waiting for this operation to finish using something like:

ms.Position = 0;
await newBlob.UploadFromStreamAsync(ms);

or use of sync version of the same method:

ms.Position = 0;
newBlob.UploadFromStream(ms);

Upvotes: 1

Related Questions