【问题标题】:How to Delete Blob From Private Azure Blob Storage Container如何从私有 Azure Blob 存储容器中删除 Blob
【发布时间】:2020-04-09 09:34:38
【问题描述】:

我正在尝试使用 deleteBlobIfExists() npm 包中的 deleteBlobIfExists() 函数从私有 blob 容器中删除 blob。但是,当函数执行时,result 总是返回为false,这意味着 blob“不存在”。但是这个blob确实存在。我只是假设它找不到 blob,因为容器的访问权限设置为“私有”。帮忙?

const blobService = azure.createBlobService();
blobService.deleteBlobIfExists("my-blob-container", "my-blob", (err, result) => {
   if(err) {
      console.log(err);
   }
});

【问题讨论】:

  • 你确定你使用azure.createBlobService()的连接选项是正确的,你为什么不尝试使用相同的BlobService查询my-blob
  • 如果你的容器的访问级别是私有的,请使用azure.createBlobService(<connection string>)创建blob服务。更多详情请参考azure.github.io/azure-storage-node/global.html

标签: node.js azure azure-blob-storage


【解决方案1】:

如果您的容器的访问级别是私有的,您在使用azure.createBlobService()创建blob客户端时需要提供存储连接字符串或帐户名和帐户密钥。

另外,sdk azure-storage 是 Azure Storage nodejs V2。它是一个旧版 SDK。我建议你使用sdk @azure/storage-blob。它是最新的 SDK。使用方法请参考以下步骤

  1. 创建 sp
az ad sp create-for-rbac -n <your-application-name> --skip-assignment
az keyvault set-policy --name <your-key-vault-name> --spn $AZURE_CLIENT_ID --secret-permissions backup delete get list purge recover restore set

  1. 创建 .env 文件
AZURE_TENANT_ID=<tenant id>
AZURE_CLIENT_ID=<app id>
AZURE_CLIENT_SECRET=<password>
  1. 安装包
npm install @azure/identity
npm install @azure/storage-blob
  1. 代码
var storage = require("@azure/storage-blob")
const { DefaultAzureCredential } = require("@azure/identity");

const defaultAzureCredential = new DefaultAzureCredential();
  const blobclient = new storage.BlobServiceClient("<blob url>",defaultAzureCredential)
  if(blobClient.exists()){

    blobClient.delete()

  }


【讨论】:

    【解决方案2】:

    如果您在 blob 创建事件后不久调用它,听起来您与 Azure 存在竞争条件。

    【讨论】:

    • 是的,就是这样。如果我的 API 端点中的其他逻辑失败,我已经编写了一个方法来删除我刚刚添加到 Azure 的任何 blob。由于我刚刚创建了 blob,doesExist 方法每次都返回 false。我通过使用 setInterval() 并在几秒钟后调用该方法几次来解决这个问题。
    【解决方案3】:

    我确认 Jim Xu 所说的 - 在调用时添加您的连接字符串

    azure.createBlobService()
    

    它会成功删除 blob。我尝试使用快速入门示例代码,并能够成功删除私有容器中的 blob。

    const CONNECT_STR = process.env.CONNECT_STR;
    console.log('\nDeleting blob...');
    
    // Delete blob
    const blobService = azure.createBlobService(CONNECT_STR);
    blobService.deleteBlobIfExists(containerName, blobName, (err, result) => {
        if(err) {
           console.log(err);
        }
     });
    
    console.log("Blob was deleted successfully.");
    

    【讨论】:

    • 文档说createBlobService“创建一个新的 {@link BlobService} 对象。如果没有提供 storageaccount 或 storageaccesskey,将使用 AZURE_STORAGE_CONNECTION_STRING 和 AZURE_STORAGE_ACCOUNT 和 AZURE_STORAGE_ACCESS_KEY 环境变量。”我的 .env 文件中有连接字符串,我可以很好地创建 blob 服务。
    猜你喜欢
    • 2017-05-20
    • 2020-09-05
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2022-01-04
    相关资源
    最近更新 更多