1
votes

In Azure blob upload, a file is overwritten if you upload a new file with the same file name (in the same container).

I would like to rename the new file before saving it, to avoid overwriting any files - Is this possible?

Scenario:

  1. Upload file "Image.jpg" to container "mycontainer"
  2. Upload file "Image.jpg" to container "mycontainer" (with different content)
  3. Rename second "Image.png" to "Image_{guid}.jpg" before saving it to "mycontainer".
3

3 Answers

0
votes

You cannot rename a blob (there's no API for it). Your options:

  • check if blob name exists, prior to uploading, and choosing a different name for your about-to-be-uploaded blob if the name is already in use
  • simulate rename by copying existing blob to new blob of different name, then deleting original blob

As @juunas pointed out in comments: You'd have to manage your workflow to avoid potential race condition regarding checking for existence, renaming, etc.

0
votes

I recommend using an "If-None-Match: *" conditional header (sometimes known as "If-Not-Exists" in the client libraries). If you include this header on either your PutBlob or PutBlockList operations, the call will fail and data will not be overwritten. You can catch this client-side and retry the upload operation (with a different blob name.)

This has two advantages over checking to see if the blob exists before uploading. First, you no longer have the potential race condition. Second, calling Exists() adds a lot of additional overhead - an additional HTTP call for every upload, which is significant unless your blobs are quite large or latency doesn't matter. With the access condition, you only need multiple calls when the name collides, which should hopefully be a rare case.

Of course, it might be easier / cleaner to just always use the GUID, then you don't have to worry about it.

0
votes

Needing to rename may be indicative of an anti-pattern. If your ultimate goal is to change the name of the file when downloaded, you can do so and keep the blob name abstract and unique.

You can set the http download filename by assigning ContentDisposition property with

attachment;filename="yourfile.txt"

This will ensure that the header is set when the blob is accessed either as public or a SAS url.