你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的 Azure 存储 Blob 客户端库 - 版本 12.28.0

Azure 存储 Blob 是云Microsoft的对象存储解决方案。 Blob 存储已针对存储大量非结构化数据进行了优化。 非结构化数据是不符合特定数据模型或定义的数据,例如文本或二进制数据。

此项目在 JavaScript 中提供了一个客户端库,使Microsoft Azure 存储 Blob 服务易于使用。

使用此包中的客户端库可以:

  • 获取/设置 Blob 服务属性
  • Create/List/Delete Containers
  • 创建/读取/列表/更新/删除块 Blob
  • 创建/读取/列表/更新/删除页 Blob
  • 创建/读取/列表/更新/删除追加 Blob

Key links

Getting started

当前支持的环境

See our support policy for more details.

Prerequisites

安装包

安装适用于 JavaScript 的 Azure 存储 Blob 客户端库的首选方法是使用 npm 包管理器。 在终端窗口中键入以下内容:

npm install @azure/storage-blob

对客户端进行身份验证

Azure 存储支持多种方式进行身份验证。 若要与 Azure Blob 存储服务交互,需要创建存储客户端的实例-BlobServiceClientContainerClientBlobClient。 请参阅 示例,了解如何创建 BlobServiceClient,了解有关身份验证的详细信息。

Azure Active Directory

Azure Blob 存储服务支持使用 Azure Active Directory 对其 API 的请求进行身份验证。 @azure/identity 包提供了应用程序可用于执行此操作的各种凭据类型。 有关更多详细信息和示例,请参阅 自述文件以获取更多详细信息和示例。

Compatibility

此库与 Node.js 和浏览器兼容,并针对 LTS Node.js 版本(>=8.16.0)和最新版本的 Chrome、Firefox 和 Edge 进行验证。

Web Workers

此库要求某些 DOM 对象在浏览器中使用时全局可用,Web 辅助角色默认不提供这些对象。 需要填充这些内容以使此库在 Web 辅助角色中正常工作。

有关详细信息,请参阅我们的 文档,了解如何在 Web 辅助角色中使用 Azure SDK for JS

此库依赖于以下 DOM API,这些 API 需要在 Web 辅助角色中使用时加载外部填充:

Node.js 和浏览器之间的差异

Node.js 和浏览器运行时之间存在差异。 开始使用此库时,请注意标有 “仅在NODE.JS运行时中可用”的 API 或类“仅在浏览器中可用”

  • 如果 blob 保存 gzipdeflate 格式的压缩数据,并相应地设置其内容编码,则下载行为在 Node.js 和浏览器之间有所不同。 在 Node.js 存储客户端将以压缩格式下载 blob,而在浏览器中,数据将以非压缩格式下载。
功能、接口、类或函数仅在 Node.js 中可用
  • 基于帐户名称和帐户密钥的共享密钥授权
    • StorageSharedKeyCredential
  • 共享访问签名(SAS) 生成
    • generateAccountSASQueryParameters()
    • generateBlobSASQueryParameters()
  • 并行上传和下载。 请注意,Node.js 和浏览器都提供了 BlockBlobClient.uploadData()
    • BlockBlobClient.uploadFile()
    • BlockBlobClient.uploadStream()
    • BlobClient.downloadToBuffer()
    • BlobClient.downloadToFile()
功能、接口、类或函数仅在浏览器中可用
  • 并行上传和下载
    • BlockBlobClient.uploadBrowserData()

JavaScript Bundle

若要在浏览器中使用此客户端库,首先需要使用捆绑程序。 For details on how to do this, please refer to our bundling documentation.

CORS

如果需要为浏览器进行开发,则需要为存储帐户设置 跨域资源共享(CORS) 规则。 转到 Azure 门户和 Azure 存储资源管理器,找到存储帐户,为 Blob/队列/文件/表服务创建新的 CORS 规则。

例如,可以创建以下 CORS 设置进行调试。 但请根据生产环境中的要求仔细自定义设置。

  • 允许的源: *
  • 允许的谓词:DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
  • 允许的标头: *
  • 公开的标头: *
  • 最大年龄(秒):86400

Key concepts

Blob 存储专为:

  • 直接向浏览器提供图像或文档。
  • 存储用于分布式访问的文件。
  • 流式传输视频和音频。
  • 写入日志文件。
  • 存储用于备份和还原、灾难恢复和存档的数据。
  • 存储数据以供本地或 Azure 托管服务进行分析。

Blob 存储提供三种类型的资源:

  • The storage account used via BlobServiceClient
  • A container in the storage account used via ContainerClient
  • A blob in a container used via BlobClient

Examples

导入包

若要使用客户端,请将包导入文件:

import * as AzureStorageBlob from "@azure/storage-blob";

或者,选择性地仅导入所需的类型:

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

创建 Blob 服务客户端

BlobServiceClient 需要 Blob 服务的 URL 和访问凭据。 它还可以选择接受 options 参数中的某些设置。

包含来自 DefaultAzureCredential 包的 @azure/identity

实例化 BlobServiceClient 的建议方法

设置:参考 - 从客户端应用程序使用 Azure Active Directory 授权访问 blob 和队列 - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-app

  • 注册新的 AAD 应用程序并授予代表已登录用户访问 Azure 存储的权限

    • 在 Azure Active Directory 中注册新应用程序(在 azure-portal 中) - https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app
    • API permissions 部分中,选择 Add a permission 并选择 Microsoft APIs
    • 选择 Azure Storage,然后选择 user_impersonation 旁边的复选框,然后单击 Add permissions。 这样,应用程序就可以代表已登录用户访问 Azure 存储。
  • 在 Azure 门户中使用 RBAC 授予对 Azure Blob 数据的访问权限

  • 示例的环境设置

    • 在 AAD 应用程序的概述页中,记下 CLIENT IDTENANT ID。 在“证书 & 机密”选项卡中,创建机密并记下。
    • 请确保已将AZURE_TENANT_ID、AZURE_CLIENT_ID AZURE_CLIENT_SECRET作为环境变量成功执行示例(可以利用 process.env)。
import { DefaultAzureCredential } from "@azure/identity";
import { BlobServiceClient } from "@azure/storage-blob";

// Enter your storage account name
const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential,
);

有关使用此方法的完整示例,请参阅 Azure AD 身份验证示例

[注意 - 上述步骤仅适用于 Node.js]

使用连接字符串

或者,可以使用具有完整连接字符串作为参数的 BlobServiceClient 静态方法实例化 fromConnectionString()。 (可以从 Azure 门户获取连接字符串。[仅在 NODE.JS RUNTIME 中可用]

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

const connStr = "<connection string>";

const blobServiceClient = BlobServiceClient.fromConnectionString(connStr);

StorageSharedKeyCredential

或者,通过将帐户名称和帐户密钥作为参数传递来实例化具有 BlobServiceClientStorageSharedKeyCredential。 (可以从 Azure 门户获取帐户名称和帐户密钥。[仅在 NODE.JS RUNTIME 中可用]

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

const account = "<account>";
const accountKey = "<accountkey>";

// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  sharedKeyCredential,
);

使用 SAS 令牌

此外,还可以使用共享访问签名(SAS)实例化 BlobServiceClient。 可以从 Azure 门户获取 SAS 令牌,也可以使用 generateAccountSASQueryParameters()生成一个。

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

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";

const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net?${sas}`);

创建新容器

使用 BlobServiceClient.getContainerClient() 获取容器客户端实例,然后创建新的容器资源。

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

// Create a container
const containerName = `newcontainer${new Date().getTime()}`;
const containerClient = blobServiceClient.getContainerClient(containerName);
const createContainerResponse = await containerClient.create();
console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);

列出容器

使用 BlobServiceClient.listContainers() 函数通过新的 for-await-of 语法循环访问容器:

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
const containers = blobServiceClient.listContainers();
for await (const container of containers) {
  console.log(`Container ${i++}: ${container.name}`);
}

或者不使用 for-await-of

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
const iter = blobServiceClient.listContainers();
let { value, done } = await iter.next();
while (!done) {
  console.log(`Container ${i++}: ${value.name}`);
  ({ value, done } = await iter.next());
}

此外,通过 byPage()也支持分页列出:

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
for await (const page of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) {
  for (const container of page.containerItems) {
    console.log(`Container ${i++}: ${container.name}`);
  }
}

For a complete sample on iterating containers please see samples/v12/typescript/src/listContainers.ts.

通过上传数据创建 Blob

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

const containerName = "<container name>";
const containerClient = blobServiceClient.getContainerClient(containerName);

const content = "Hello world!";
const blobName = `newblob ${+new Date()}`;
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
console.log(
  `Upload block blob ${blobName} successfully with request ID: ${uploadBlobResponse.requestId}`,
);

列出容器内的 Blob

类似于列出容器。

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

const containerName = "<container name>";
const containerClient = blobServiceClient.getContainerClient(containerName);

let i = 1;
const blobs = containerClient.listBlobsFlat();
for await (const blob of blobs) {
  console.log(`Blob ${i++}: ${blob.name}`);
}

For a complete sample on iterating blobs please see samples/v12/typescript/src/listBlobsFlat.ts.

下载 blob 并将其转换为字符串(Node.js)

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

const containerName = "<container name>";
const blobName = "<blob name>";
const containerClient = blobServiceClient.getContainerClient(containerName);
const blobClient = containerClient.getBlobClient(blobName);

// Get blob content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
const downloadBlockBlobResponse = await blobClient.download();
if (downloadBlockBlobResponse.readableStreamBody) {
  const downloaded = await streamToString(downloadBlockBlobResponse.readableStreamBody);
  console.log(`Downloaded blob content: ${downloaded}`);
}

async function streamToString(stream: NodeJS.ReadableStream): Promise<string> {
  const result = await new Promise<Buffer<ArrayBuffer>>((resolve, reject) => {
    const chunks: Buffer[] = [];
    stream.on("data", (data) => {
      chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
    });
    stream.on("end", () => {
      resolve(Buffer.concat(chunks));
    });
    stream.on("error", reject);
  });
  return result.toString();
}

下载 Blob 并将其转换为字符串(浏览器)。

Please refer to the JavaScript Bundle section for more information on using this library in the browser.

import { BlobServiceClient } from "@azure/storage-blob";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  new DefaultAzureCredential(),
);

const containerName = "<container name>";
const blobName = "<blob name>";
const containerClient = blobServiceClient.getContainerClient(containerName);
const blobClient = containerClient.getBlobClient(blobName);

// Get blob content from position 0 to the end
// In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
const downloadBlockBlobResponse = await blobClient.download();
const blobBody = await downloadBlockBlobResponse.blobBody;
if (blobBody) {
  const downloaded = await blobBody.text();
  console.log(`Downloaded blob content: ${downloaded}`);
}

A complete example of simple scenarios is at samples/v12/typescript/src/sharedKeyAuth.ts.

Troubleshooting

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以通过在 setLogLevel中调用 @azure/logger 在运行时启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

Next steps

更多代码示例:

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

另请参阅 存储特定指南,了解有关为存储库设置测试环境的其他信息。