如何使用 Azure JavaScript SDK 访问 blob 元数据?

How to access blob metadata using the Azure JavaScript SDK?

如何通过 JavaScript SDK 在 Azure 中读取 blob 的元数据?

当我迭代从指定容器返回的 blob 时,我看到一个元数据 属性:

但它是未定义的,即使肯定有与 blob 关联的元数据:

我还需要做些什么来填充元数据吗?

import { BlobServiceClient, SharedKeyCredential } from "@azure/storage-blob";

const account = "<redacted>";
const accountKey = "<redacted>";
const sharedKeyCredential = new SharedKeyCredential(account, accountKey);
const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net`, sharedKeyCredential);
const containerClient = blobServiceClient.getContainerClient(podcastName);

const blobs = await containerClient.listBlobsFlat({ include: ["metadata"] });
for await (const blob of blobs) {
  console.log(blob.name);
  //blob.metadata is undefined
}

// package.json relevant dependencies
"dependencies": {
  "@azure/storage-blob": "^12.0.0-preview.2
}

您可以使用 getBlobMetadata 方法获取 blob 的属性。

var storage = require('azure-storage');
var blobService = storage.createBlobService();
var containerName = 'your-container-name';
var blobName = 'my-awesome-blob';
blobService.getBlobMetadata(containerName, blobName, function(err, result, response) {
    if (err) {
        console.error("Couldn't fetch metadata for blob %s", blobName);
        console.error(err);
    } else if (!response.isSuccessful) {
        console.error("Blob %s wasn't found container %s", blobName, containerName);
    } else {
        console.log("Successfully fetched metadata for blob %s", blobName);
        console.log(result.metadata);
    }
});

更多的细节,你可以参考这篇article

我测试它是空的,然后我使用 getProperties() 来获取元数据并且它有效,你可以试试。

const containerName = "test";
const blobName = "test.txt";


let response;
let marker;

do {
    response = await containerURL.listBlobFlatSegment(aborter);
    marker = response.marker;
    for(let blob of response.segment.blobItems) {

        const url= BlockBlobURL.fromContainerURL(containerURL,blob.name);
        const pro=await url.getProperties(aborter);

        console.log(pro.metadata);

    }
} while (marker);

// You can try this: 
for await (const blob of containerClient.listBlobsFlat()) {
    const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
    const meta = (await blockBlobClient.getProperties()).metadata;
    console.log(meta);
    // process metadata
}
  • 我假设您已经声明了 blockBlobClientcontainerClient
  • 如果你还没有声明blockBlobClientcontainerClient,那么你可以参考here

在 v12 中,您可以在列出 blob 时通过传递选项 includeMetadata: true

来检索元数据
await containerClient.listBlobsFlat({ includeMetadata: true });

https://github.com/Azure/azure-sdk-for-js/blob/d2730549e078571df008e929f19c07aaf8f9efd9/sdk/storage/storage-blob/test/containerclient.spec.ts#L198