快速入门:适用于 C++ 的 Azure Blob 存储客户端库 v12Quickstart: Azure Blob Storage client library v12 for C++

适用于 C++ 的 Azure Blob 存储客户端库 v12 入门。Get started with the Azure Blob Storage client library v12 for C++. Azure Blob 存储是 Microsoft 提供的适用于云的对象存储解决方案。Azure Blob Storage is Microsoft's object storage solution for the cloud. 请按照步骤操作,安装程序包并试用基本任务的示例代码。Follow steps to install the package and try out example code for basic tasks. Blob 存储最适合存储巨量的非结构化数据。Blob Storage is optimized for storing massive amounts of unstructured data.

使用适用于 C++ 的 Azure Blob 存储客户端库 v12 完成以下操作:Use the Azure Blob Storage client library v12 for C++ to:

  • 创建容器Create a container
  • 将 blob 上传到 Azure 存储Upload a blob to Azure Storage
  • 列出容器中所有的 blobList all of the blobs in a container
  • 将 blob 下载到本地计算机Download the blob to your local computer
  • 删除容器Delete a container

资源:Resources:

备注

本文中所述的功能现在可用于具有分层命名空间的帐户。The features described in this article are now available to accounts that have a hierarchical namespace. 若要查看限制,请参阅 Azure Data Lake Storage Gen2 中可用的 Blob 存储功能一文。To review limitations, see the Blob storage features available in Azure Data Lake Storage Gen2 article.

先决条件Prerequisites

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 C++ 的 Azure Blob 存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Blob Storage client library v12 for C++.

安装包Install the packages

如果尚未安装 LibCurl 和 LibXML2 包,请使用 vcpkg install 命令进行安装。If you haven't already, install the LibCurl and LibXML2 packages by using the vcpkg install command.

vcpkg.exe install libxml2:x64-windows curl:x64-windows

按照 GitHub 上的说明获取并构建适用于 C++ 的 Azure SDKFollow the instructions on GitHub to acquire and build the Azure SDK for C++.

创建项目Create the project

在 Visual Studio 中创建 C++ Windows 控制台应用程序“BlobQuickstartV12”。In Visual Studio, create a new C++ console application for Windows called BlobQuickstartV12.

用于配置新的 C++ Windows 控制台应用的 Visual Studio 对话框

将以下库添加到项目中:Add the following libraries to the project:

  • libcurl.liblibcurl.lib
  • libxml2.liblibxml2.lib
  • bcrypt.libbcrypt.lib
  • Crypt32.LibCrypt32.Lib
  • WS2_32.LibWS2_32.Lib
  • azure-core.libazure-core.lib
  • azure-storage-common.libazure-storage-common.lib
  • azure-storage-blobs.libazure-storage-blobs.lib

从 Azure 门户复制凭据Copy your credentials from the Azure portal

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

配置存储连接字符串Configure your storage connection string

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure Blob 存储最适合存储巨量的非结构化数据。Azure Blob Storage is optimized for storing massive amounts of unstructured data. 非结构化数据是不遵循特定数据模型或定义的数据(如文本或二进制数据)。Unstructured data is data that doesn't adhere to a particular data model or definition, such as text or binary data. Blob 存储提供了三种类型的资源:Blob Storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的容器A container in the storage account
  • 容器中的 blobA blob in the container

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

Blob 存储体系结构的图示

使用以下 C++ 类与这些资源进行交互:Use the following C++ classes to interact with these resources:

  • BlobServiceClientBlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • BlobContainerClientBlobContainerClient 类可用于操纵 Azure 存储容器及其 blob。BlobContainerClient: The BlobContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClientBlobClient 类可用于操纵 Azure 存储 blob。BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs. 这是所有专用 blob 类的基类。It's the base class for all specialized blob classes.
  • BlockBlobClientBlockBlobClient 类可用于操纵 Azure 存储块 blob。BlockBlobClient: The BlockBlobClient class allows you to manipulate Azure Storage block blobs.

代码示例Code examples

这些示例代码片段演示如何使用适用于 C++ 的 Azure Blob 存储客户端库执行以下任务:These example code snippets show you how to do the following tasks with the Azure Blob Storage client library for C++:

添加包含文件Add include files

从项目目录中执行以下操作:From the project directory:

  1. 在 Visual Studio 中打开 BlobQuickstartV12.sln 解决方案文件Open the BlobQuickstartV12.sln solution file in Visual Studio
  2. 在 Visual Studio 中,打开 BlobQuickstartV12.cpp 源文件Inside Visual Studio, open the BlobQuickstartV12.cpp source file
  3. 删除自动生成的 main 中的所有代码Remove any code inside main that was autogenerated
  4. 添加 #include 语句Add #include statements
// Prevent warnings from using std library
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <stdlib.h>
#include "azure\storage\blob.hpp"

获取连接字符串Get the connection string

下面的代码从配置存储连接字符串中创建的环境变量中检索存储帐户的连接字符串。The code below retrieves the connection string for your storage account from the environment variable created in Configure your storage connection string.

main() 中添加此代码:Add this code inside main():

// Retrieve the connection string for use with the application. The storage
// connection string is stored in an environment variable on the machine
// running the application called AZURE_STORAGE_CONNECTION_STRING.
const char* connectionString = std::getenv("AZURE_STORAGE_CONNECTION_STRING");

创建容器Create a container

调用 CreateFromConnectionString 函数,创建 BlobContainerClient 类的实例。Create an instance of the BlobContainerClient class by calling the CreateFromConnectionString function. 然后调用 Create 方法,在存储帐户中创建实际容器。Then call Create to create the actual container in your storage account.

重要

容器名称必须为小写。Container names must be lowercase. 有关命名容器和 Blob 的详细信息,请参阅命名和引用容器、Blob 和元数据For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

将此代码添加到 main() 的末尾:Add this code to the end of main():

using namespace Azure::Storage::Blobs;

std::string containerName = "myblobcontainer";

// Initialize a new instance of BlobContainerClient
BlobContainerClient containerClient =
    BlobContainerClient::CreateFromConnectionString(connectionString, containerName);

try
{
    // Create the container. This will throw an exception if the container already exists.
    std::cout << "Creating container: " << containerName << std::endl;
    containerClient.Create();
}
catch (std::runtime_error& e)
{
    // The container already exists
    std::cout << "Error: " << e.what() << std::endl;
}

将 blob 上传到容器中Upload blobs to a container

以下代码片段:The following code snippet:

  1. 声明一个包含“Hello Azure!”的字符串。Declares a string containing "Hello Azure!".
  2. 对在创建容器部分创建的容器调用 GetBlockBlobClient,获取对 BlockBlobClient 对象的引用。Gets a reference to a BlockBlobClient object by calling GetBlockBlobClient on the container from the Create a container section.
  3. 通过调用 UploadFrom 函数,将字符串上传到 blob。Uploads the string to the blob by calling the UploadFrom function. 此函数将创建 Blob(如果该 Blob 尚不存在),或者更新 Blob(如果该 Blob 已存在)。This function creates the blob if it doesn't already exist, or updates it if it does.

将此代码添加到 main() 的末尾:Add this code to the end of main():

std::string blobName = "blob.txt";
std::string blobContent = "Hello Azure!";

// Create the block blob client
BlockBlobClient blobClient = containerClient.GetBlockBlobClient(blobName);

// Upload the blob
std::cout << "Uploading blob: " << blobName << std::endl;
blobClient.UploadFrom(reinterpret_cast<const uint8_t*>(blobContent.data()), blobContent.size());

列出容器中的 blobList the blobs in a container

通过调用 ListBlobsFlatSegment 函数,列出容器中的 blob。List the blobs in the container by calling the ListBlobsFlatSegment function. 只向容器添加了一个 blob,所以此操作只返回这一个 blob。Only one blob has been added to the container, so the operation returns just that blob.

将此代码添加到 main() 的末尾:Add this code to the end of main():

std::cout << "Listing blobs..." << std::endl;

auto response = containerClient.ListBlobsFlatSegment();

ListBlobsFlatSegmentResult result = response.ExtractValue();

for (BlobItem blobItem : result.Items)
{
    std::cout << "Blob name: " << blobItem.Name.data() << std::endl;
}

下载 BlobDownload blobs

获取上传的 Blob 的属性。Get the properties of the uploaded blob. 然后,使用上传的 blob 的属性,声明新的 std::string 对象并调整其大小。Then, declare and resize a new std::string object by using the properties of the uploaded blob. 通过在 BlobClient 基类中调用 DownloadTo 函数,将以前创建的 blob 下载到新的 std::string 对象。Download the previously created blob into the new std::string object by calling the DownloadTo function in the BlobClient base class. 最后,显示下载的 blob 数据。Finally, display the downloaded blob data.

将此代码添加到 main() 的末尾:Add this code to the end of main():

auto properties = *blobClient.GetProperties();
std::string downloadedBlob = "";
downloadedBlob.resize(static_cast<std::size_t>(properties.ContentLength));
blobClient.DownloadTo(reinterpret_cast<uint8_t*>(&downloadedBlob[0]), blobContent.size());
std::cout << "Downloaded blob contents: " << downloadedBlob << std::endl;

删除 BlobDelete a Blob

以下代码通过调用 BlobClient 函数,从 Azure Blob 存储容器中删除 blob。The following code deletes the blob from the Azure Blob Storage container by calling the BlobClient.Delete function.

std::cout << "Deleting blob: " << blobName << std::endl;
blobClient.Delete();

删除容器Delete a container

以下代码使用 BlobContainerClient.Delete 来删除整个容器,从而清除该应用创建的资源。The following code cleans up the resources the app created by deleting the entire container by using BlobContainerClient.Delete.

将此代码添加到 main() 的末尾:Add this code to the end of main():

std::cout << "Deleting blob: " << blobName << std::endl;
blobClient.Delete();

运行代码Run the code

此应用将创建一个容器,并将文本文件上传到 Azure Blob 存储。This app creates a container and uploads a text file to Azure Blob Storage. 示例随后列出容器中的 Blob,下载文件并显示文件内容。The example then lists the blobs in the container, downloads the file, and displays the file contents. 最后,应用会删除 blob 和容器。Finally, the app deletes the blob and the container.

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Blob Storage v12 - C++ quickstart sample
Creating container: myblobcontainer
Uploading blob: blob.txt
Listing blobs...
Blob name: blob.txt
Downloaded blob contents: Hello Azure!
Deleting blob: blob.txt
Deleting container: myblobcontainer

后续步骤Next steps

本快速入门介绍了如何使用 C++ 上传、下载和列出 Blob。In this quickstart, you learned how to upload, download, and list blobs using C++. 此外,还介绍了如何创建和删除 Azure Blob 存储容器。You also learned how to create and delete an Azure Blob Storage container.

若要查看 C++ Blob 存储示例,请继续参考以下内容:To see a C++ Blob Storage sample, continue to: