Danielle
Danielle

Reputation: 1486

Delete all files with a specific name, and * extension at Azure Blob Storage

I have a process where a client uploads a document. This document can be in the form of a PDF, JPG or PNG file only and it should be reuploaded once a year (it is an errors and omissions insurance policy).

I am saving this file in a container.

For deleting files from anywhere at the application, I have this function (Node):

deleteFromBlob = async function (account, accountKey, containerName, blobFolder, blobName) {
    try {
        const {
            BlobServiceClient,
            StorageSharedKeyCredential
        } = require("@azure/storage-blob");
        const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
        const blobServiceClient = new BlobServiceClient(
            `https://${account}.blob.core.windows.net`,
            sharedKeyCredential
        );
    
        const containerClient = blobServiceClient.getContainerClient(containerName);
        const blockBlobClient = containerClient.getBlockBlobClient(blobFolder + '/' + blobName);
        const uploadblobResponse = await blockBlobClient.deleteIfExists()
        return true
    }
    catch(e) {
        return false
    }
}

And this works perfect when I know the file name and extension I want to delete, like "2448.pdf":

let deleteFile = await utils.deleteFromBlob(account, accountKey, "agents", "/eopolicies/", userData.agentid.toString() + ".pdf" ) 

But the problem Im facing is that the function above is to delete a file I know exists; for example, if the agent ID is 2448 and he uploads "policy.pdf" I save it as "2448.pdf" for easy file identification.

The problem Im facing is if the agent uploaded a .PNG last year. a .DOC a year before, and a .PDF now. If that's the case, I want to delete 2448.* and keep only the latest version of the document.

So I tried changing my function to

let deleteFile = await utils.deleteFromBlob(account, accountKey, "agents", "/eopolicies/", userData.agentid.toString() + ".*" )

And of course it is not working...

I tried to find a solution and all I found is one to list the content of a folder, then loop it and delete the specific file I want; but that will not work for me since there are 37,000 EO policies on that folder.

Is there a way to delete files with a specific name, and whatever extension?

Thanks.

Upvotes: 0

Views: 663

Answers (1)

piximi
piximi

Reputation: 23

I've never tried using a wildcard on the extension side of the file name. However, I would iterate through the files in the directory and find the one that contains the specific string you are looking for. Get it's index, and delete from there.

Upvotes: 1

Related Questions