Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow the overwriting of blobs from my ASP.NET Core application?

Users can upload images when a record is created, when you edit that record and try to upload new images there is an error of "This blob already exists". Is there a way that I can enable the overwriting of blobs with the same name in my application?

Here is my code that handles the update process.

It's important to note that I create three iterations of an image for the sake of the application so I have included the array that has that information.

CarController.cs

private readonly int[] sizeArray = new int[] { 700, 350, 150 };

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
        //Create the Car
                _carService.InsertCar(car);

                //Get the ID of the newly created car
                int id = car.Id;

                //Define the container name for Azure Storage
                string strContainerName = "uploads";                               

                //Blob Client
                BlobServiceClient blobServiceClient = new BlobServiceClient(accessKey);
                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(strContainerName);

                //Iterate over the array of image sizes
                foreach (var imageSize in sizeArray)
                {
                    try
                    {
                        //Pass image to image processor and save to the blob location
                        string fileName = "car/" + id + "/car-image-" + imageSize + ".jpg";
                        Stream returnStream = ProcessImage(imageSize, car);
                        containerClient.UploadBlob(fileName, returnStream);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }                   
                return RedirectToAction(nameof(Index));
            }            
            return View(car);
        }
like image 970
Yanayaya Avatar asked Dec 20 '25 23:12

Yanayaya


2 Answers

I think you're using v12 client library.

Then there is no blob overwriting method in container level, you should use Upload(Stream content, bool overwrite = false) method of the BlobClient. Sample code like below:

            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(mycontainer);
            BlobClient blobClient = containerClient.GetBlobClient("blob_name");

            blobClient.Upload(your_stream, overwrite: true);
like image 139
Ivan Yang Avatar answered Dec 22 '25 12:12

Ivan Yang


If you want to specify both overwrite: true and use BlobStorageOptions at the same time, this is the implementation of the Upload(...) overload with the bool overwrite parameter:

public virtual Response<BlobContentInfo> Upload(
    Stream content,
    bool overwrite = false,
    CancellationToken cancellationToken = default) =>
    Upload(
        content,
        conditions: overwrite ? null : new BlobRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
        cancellationToken: cancellationToken);

Which leads to the following overload (some code omitted for brevity):

public virtual Response<BlobContentInfo> Upload(
    ....
    BlobRequestConditions conditions = default,
    ....) =>
    StagedUploadInternal(
        content,
        new BlobUploadOptions
        {
            ...
            Conditions = conditions,
            ...
        },
        ...

So actually overwrite is the default as soon as you specify your own BlobUploadOptions without any specific IfNoneMatch option.

This is also supported by the comments on the function:

// Summary:
//     The Azure.Storage.Blobs.BlobClient.UploadAsync(System.IO.Stream,Azure.Storage.Blobs.Models.BlobUploadOptions,System.Threading.CancellationToken)
//     operation overwrites the contents of the blob, creating a new block blob if none
//     exists. Overwriting an existing block blob replaces any existing metadata on
//     the blob. Set access conditions through Azure.Storage.Blobs.Models.BlobUploadOptions.Conditions
//     to avoid overwriting existing data.

Note that new ETag(Constants.Wildcard) is the same as new ETag("*"), since the class containing Constants.Wildcard is internal.

Code copied from BlobClient.cs.

like image 38
Willem Avatar answered Dec 22 '25 11:12

Willem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!