Rui Santos
Rui Santos

Reputation: 547

Check if blob exists in Azure

I'm wondering if there is a way to check if a blob exists in a container?

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

I've tried this but im getting this message whenever the blob does not exists:

BlobNotFoundThe specified blob does not exist.

If exists, the code returns 'exists' naturally. I'm not interested in listing all blobs in the container and iterating until I find a match cause I have a lot of blobs.

Upvotes: 0

Views: 1297

Answers (3)

Tim
Tim

Reputation: 1471

Though older post, below is azure java client sample code, in case if it helps.

//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
     }
});

Upvotes: 0

Gary Liu
Gary Liu

Reputation: 13918

When the blob does not exist, the function getBlob will raise a ServiceException exception and exit the PHP progress, the following code will not work.

Please try to add the try catch statement in your code, E.G.

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

Upvotes: 2

Pedro G. Dias
Pedro G. Dias

Reputation: 3222

so:

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

Should give you what you're after.

Upvotes: 1

Related Questions