检查Azure中是否存在blob


Check if blob exists in Azure

我想知道是否有办法检查容器中是否存在blob?

    $blob = $blobRestProxy->getBlob("mycontainer", "myblobname");
    if($blob){
        return 'exists';
    } else {
        return 'not exists';
    }

我试过了,但每当blob不存在时,我都会收到这样的消息:

BlobNotFound指定的blob不存在。

如果存在,则代码自然返回"exists"。我对在容器中列出所有Blob并迭代直到找到匹配项不感兴趣,因为我有很多Blob。

当blob不存在时,函数getBlob将引发ServiceException异常并退出PHP进程,以下代码将不起作用。

请尝试在代码中添加try-catch语句,例如

try {
    $blob = $tableRestProxy->getBlob("mycontainer", "myblobname");
    return 'exists';
} catch (ServiceException $e) {
    return 'not exists';
} 

so:

$exists = $storageClient->blobExists(<container name>, <blob name>);

应该给你想要的。

虽然是较老的帖子,但下面是azure java客户端示例代码,以防有帮助。

//getting the info from external configuration
String accountName = getStorageAccountName();
String accessKey = getAccessKey();
String container = getContainerName();
//create connection string
String connString =  String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",accountName,accessKey);
// create account
CloudStorageAccount account=  CloudStorageAccount.parse(connString );
// create client
CloudBlobClient blobClient = account.createCloudBlobClient();
// create container
CloudBlobContainer container = blobClient.getContainerReference(container);
// fetch item from list
Iterable<ListBlobItem> blobItems = container.listBlobs();
blobItems .forEach(item -> {
    if (item instanceof CloudBlockBlob){ 
//additional condition can be added to check leased
        
        // need to check if the blob item exists first 
         if((CloudBlockBlob) blobItem).exists()){
             //custom business logic 
         }
       
        // to check container exists and perform logic use below
        // ((CloudBlobContainer) item.getContainer()).exists
     }
});