Azure blob upload rename if blob name exist

a 夏天 提交于 2020-01-24 21:23:47

问题


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".

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/45709036/azure-blob-upload-rename-if-blob-name-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!