1

I am uploading a file to Azure Blob storage with this code.

Sometimes after calling this function I immediately try and access the blob it does not exists, and I assume the upload has not completed. How can I ensure the upload is complete? Possibly with a status of progress.

    public async Task<bool> PutBlobAsync(string containerName, string blobName, byte[] content, bool allowOverwrite = false, string contentType = null)
    {
        try
        {

            var containerClient = CreateAndGetContainer(containerName);
            var blobClient = containerClient.GetBlobClient(blobName);

            var blobUploadOptions = new BlobUploadOptions();

            if (!String.IsNullOrEmpty(contentType))
                blobUploadOptions.HttpHeaders = new BlobHttpHeaders { ContentType = contentType };

            if (!allowOverwrite)
                blobUploadOptions.Conditions = new BlobRequestConditions { IfNoneMatch = ETag.All };

            using (var stream = new MemoryStream())
            {
                stream.Write(content, 0, content.Length);
                stream.Position = 0;
                await blobClient.UploadAsync(stream, blobUploadOptions);
            }

            return true;
        }
        catch (RequestFailedException e)
        {
            Logger.Error(e, "PutBlobAsync");

            switch (e.Status)
            {
                case (int)HttpStatusCode.NotFound:
                case (int)HttpStatusCode.PreconditionFailed:
                    return false;
            }
            throw;
        }

    }
2
  • 2
    after uploading the blob with UploadAsync, call await blobClient.ExistsAsync() in a small loop to make sure the blob is fully available/saved before accessing it. Commented May 23 at 2:07
  • @HarshithaBathini - as I've mentioned to you in the past, there is no need to keep asking if people reviewed an answer. Also, remember that this is not an official support channel, and you should not be committing to provide specific help - this is just a community-driven Q&A site, with no SLA and no expectation of a company representative providing free support. Commented May 31 at 15:41

1 Answer 1

1

Uploading a file to Azure Blob storage

I used BlockBlobClient.UploadAsync() to upload a file, and it was immediately visible and accessible in the Azure portal right after the upload completed. The file appears correctly with the expected size and timestamp.

I tested the method with a 1 GiB file using a streaming approach, and while the Azure portal does not allow previewing large files, the blob was uploaded successfully and is available for download without any issues.

Since Azure Blob Storage provides strong consistency, the blob becomes available for access as soon as the upload completes successfully.

This makes sure the file was uploaded successfully.

BlobService.cs:

namespace BlobUploader.Services
{
    public class BlobService
    {
        private readonly string _connectionString;
        public BlobService(string connectionString)
        {
            _connectionString = connectionString;
        }
        public async Task<bool> PutBlobAsync(string containerName, string blobName, string filePath, bool allowOverwrite = false, string? contentType = null)
        {
            try
            {
                var containerClient = new BlobContainerClient(_connectionString, containerName);
                await containerClient.CreateIfNotExistsAsync();
                var blobClient = containerClient.GetBlockBlobClient(blobName);
                var blobUploadOptions = new BlobUploadOptions();
                if (!string.IsNullOrEmpty(contentType))
                {
                    blobUploadOptions.HttpHeaders = new BlobHttpHeaders
                    {
                        ContentType = contentType
                    };
                }
                if (!allowOverwrite)
                {
                    blobUploadOptions.Conditions = new BlobRequestConditions
                    {
                        IfNoneMatch = ETag.All
                    };
                }   
                using var fileStream = File.OpenRead(filePath);
                await blobClient.UploadAsync(fileStream, blobUploadOptions);
                return true;
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine($"Error uploading blob: {e.Message}");
                return false;
            }
        }
    }
}

Program.cs:

using BlobUploader.Services;
using System.Text;
string connectionString = "<Your Connectio string>"; 
string containerName = "<Your ContainerName>";
string blobName = "<Your blobName>";
string filePath = "<Your Filepath>";
var  blobService  =  new  BlobService(connectionString);
bool  result  =  await  blobService.PutBlobAsync(containerName, blobName, filePath);
Console.WriteLine($"Upload successful: {result}");

Output:

Image

blob appeared immediately in Azure Portal

Image1

Sign up to request clarification or add additional context in comments.

3 Comments

Even if UploadAsync() finishes, sometimes the file is not immediately available to read. This is because Azure Blob Storage can take a small delay to make the new file fully accessible. - This is not correct. Writes in Azure Storage are always strongly consistent. If you get a 200 status code back, that means the blob is written successfully and should be immediately available.
On the subject of small delay... I've spent all day chasing this issue. I'm writing a (small) blob using an API and uploadAsync(), but then reading the blob directly on the client (no API) using SAS and axios with a queryString time parameter to break caching. I swear that if I do an immediate read after the write I'll often get stale data, but after a few seconds the staleness issue goes away. I can step through both my client and server code and verified everything is copasetic. Argh!
@GauravMantri Thanks for the information. I have corrected my answer and updated the code to remove the extra check after the upload.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.