How to upload an image URL to Azure blob storage using C# - Biz Tech

How to upload an image URL to Azure blob storage using C#

Listen

To upload an image URL to Azure Blob Storage using C#, you can use the following steps:

  1. Install the Azure.Storage.Blobs NuGet package in your C# project.

  2. Create an instance of the BlobServiceClient class with your Azure Blob Storage account connection string:

     string connectionString = "<your Azure Blob Storage connection string>";
    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    
  3. Create a BlobContainerClient object that represents the container in which you want to upload the image:
     string containerName = "<your container name>";
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    
  4. Create a BlobClient object that represents the blob you want to upload:
     string blobName = "<your blob name>";
    BlobClient blobClient = containerClient.GetBlobClient(blobName);
    
  5. Use the UploadAsync method of the BlobClient object to upload the image URL:
     using (var client = new WebClient())
    {
        var imageBytes = client.DownloadData(imageUrl);
        using (var stream = new MemoryStream(imageBytes))
        {
            await blobClient.UploadAsync(stream, new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = "image/jpeg"
                }
            });
        }
    }
    

In the code above, imageUrl is the URL of the image you want to upload. The WebClient class is used to download the image data from the URL into a byte array. You can replace "image/jpeg" with the appropriate content type for your image.

  1. Make sure that the image URL is accessible from your environment and that your Azure Blob Storage account has permission to access it.

That’s it! With these steps, you should be able to upload an image URL to Azure Blob Storage using C#.