练习 - 将图像上传到 Azure 存储帐户

已完成

接下来我们将添加代码,以将图像上传到 Azure 存储帐户。 在此示例中,我们会将下面的图像上传到 Azure 存储容器中。

An image of the Docs mascot and the Azure mascot taking a selfie.

如果你正在使用本地计算机,可右键单击该图像,将其保存到应用程序所在的同一个文件夹中。

  1. 如果你正在 Microsoft Learn 沙盒环境中工作,请在应用程序文件夹中运行以下命令,将该图像下载到沙盒中:

    wget https://github.com/MicrosoftDocs/mslearn-connect-app-to-azure-storage/blob/main/images/docs-and-friends-selfie-stick.png?raw=true -O docs-and-friends-selfie-stick.png
    

    在这两种情况下,该图像的名称均应为 docs-and-friends-selfie-stick.png。

将图像上传到 blob 存储

若要使用 Azure 存储帐户中的单个 blob 对象,请使用 BlobClient 对象。 要获取 BlobClient 对象,请对要用于存储 blob 的容器的 BlobContainerClient 对象调用 GetBlobClient 方法。 调用 GetBlobClient 方法时,你还要在容器中为 blob 命名。 在示例中,blob 的名称将与文件名称相同。

  1. 具有 BlobClient 对象后,可以调用 Upload 方法,将文件上传到 Azure Blob 存储中。 将以下代码添加到 Program.cs 文件:

    string blobName = "docs-and-friends-selfie-stick";
    string fileName = "docs-and-friends-selfie-stick.png";
    BlobClient blobClient = container.GetBlobClient(blobName);
    blobClient.Upload(fileName, true);
    

    Upload 方法中的第二个参数用于指定系统是否可以覆盖具有相同名称的现有 blob 对象。 默认情况下,此值为 false。 在此示例中,我们将指定 true 以允许多次运行该程序。

列出 Azure Blob 存储容器中的对象

为了验证程序是否正常工作,我们将运用 Azure 存储 Blob SDK 的另一项功能,列出 blob 存储中的容器存储的对象。 可以通过对 BlobContainerClient 对象调用 GetBlobs 方法来实现此目的。 GetBlobs 方法将返回一个可分页的 BlobItem 对象列表,这些对象中包含关于容器中各个 blob 的数据。

  1. 将下面的代码添加到程序,放在你之前添加的代码后面,然后保存文件:

    var blobs = container.GetBlobs();
    foreach (var blob in blobs)
    {
        Console.WriteLine($"{blob.Name} --> Created On: {blob.Properties.CreatedOn:yyyy-MM-dd HH:mm:ss}  Size: {blob.Properties.ContentLength}");
    }
    

    此代码将对“照片”容器的 BlobContainerClient 对象调用 GetBlobs。 然后此代码会遍历每一个 Blob,并输出 Blob 的名称、创建日期和时间以及大小。 运行程序时,此代码应显示为已上传的单个图像的单个行。

  2. 最终的 Program.cs 文件应如下所示,可依此检查自己的成果。

    using System;
    using Microsoft.Extensions.Configuration;
    using System.IO;
    using Azure.Storage.Blobs;
    
    namespace PhotoSharingApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json");
    
                var configuration = builder.Build();
    
                // Get a connection string to our Azure Storage account.
                var connectionString = configuration.GetConnectionString("StorageAccount");
    
                // Get a reference to the container client object so you can create the "photos" container
                string containerName = "photos";
                BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
                container.CreateIfNotExists();
    
                // Uploads the image to Blob storage.  If a blb already exists with this name it will be overwritten
                string blobName = "docs-and-friends-selfie-stick";
                string fileName = "docs-and-friends-selfie-stick.png";
                BlobClient blobClient = container.GetBlobClient(blobName);
                blobClient.Upload(fileName, true);
    
                // List out all the blobs in the container
                var blobs = container.GetBlobs();
                foreach (var blob in blobs)
                {
                    Console.WriteLine($"{blob.Name} --> Created On: {blob.Properties.CreatedOn:yyyy-MM-dd HH:mm:ss}  Size: {blob.Properties.ContentLength}");
                }
            }
        }
    }
    

运行应用

  1. 生成并运行应用程序,以验证是否一切都正常工作,并将图像上传到 Azure Blob 存储。

    备注

    请确保在 PhotoSharingApp 目录中操作。

    dotnet run
    

祝贺

你已经掌握了使用 Azure 存储 Blob SDK 包和 Azure Blob 存储的基本知识。 如果需要,可创建另一个容器,将更多图像上传到存储帐户或删除图像,进一步进行探索。 有关详细信息,请参阅“适用于 .NET GitHub 的 Azure 存储 Blob 客户端库”页面

将图像上传到 blob 存储

若要使用 Azure 存储容器中的 Blob 对象,可使用 BlockBlobClient 对象。 BlockBlobClient 对象具有用于在容器中上传、下载、列出和删除 Blob 对象的方法。 若要获取 BlockBlobObject,请对 ContainerClient 对象调用 getBlockBlobClient 方法。 然后,你可以使用 uploadFile 方法将图像上传到 Azure 存储。

  1. 将此代码添加到 index.js 程序文件中,紧随创建容器的代码:

    const filename = 'docs-and-friends-selfie-stick.png';
    const blockBlobClient = containerClient.getBlockBlobClient(filename);
    blockBlobClient.uploadFile(filename);
    

列出 Azure Blob 存储容器中的对象

  1. 若要验证代码是否正常工作,可以对程序中的 ContainerClient 对象调用 listBlobsFlat 方法。 将此代码添加到 index.js 文件,然后保存文件:

    let blobs = containerClient.listBlobsFlat();
    let blob = await blobs.next();
    while (!blob.done) {
        console.log(`${blob.value.name} --> Created: ${blob.value.properties.createdOn}   Size: ${blob.value.properties.contentLength}`);
        blob = await blobs.next();
    }
    

    此代码将输出 Azure Blob 存储容器中的所有 Blob,并显示 Blob 的创建日期及大小。 对于此程序,该代码应输出一个表示已上传的单个图像的行。

  2. 最终的文件应如下所示。

    #!/usr/bin/env node
    require('dotenv').config();
    
    const { BlobServiceClient } = require("@azure/storage-blob");
    
    const storageAccountConnectionString = process.env.AZURE_STORAGE_CONNECTION_STRING;
    const blobServiceClient = BlobServiceClient.fromConnectionString(storageAccountConnectionString);
    
    async function main() {
    // Create a container (folder) if it does not exist
    const containerName = 'photos';
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const containerExists = await containerClient.exists()
    if ( !containerExists) {
        const createContainerResponse = await containerClient.createIfNotExists();
        console.log(`Create container ${containerName} successfully`, createContainerResponse.succeeded);
    }
    else {
        console.log(`Container ${containerName} already exists`);
    }
    
    // Upload the file
    const filename = 'docs-and-friends-selfie-stick.png';
    const blockBlobClient = containerClient.getBlockBlobClient(filename);
    blockBlobClient.uploadFile(filename);
    
    // Get a list of all the blobs in the container
    let blobs = containerClient.listBlobsFlat();
    let blob = await blobs.next();
    while (!blob.done) {
        console.log(`${blob.value.name} --> Created: ${blob.value.properties.createdOn}   Size: ${blob.value.properties.contentLength}`);
        blob = await blobs.next();
    }
    }
    main();
    

运行应用

  1. 生成并运行应用程序。

    备注

    请确保在 PhotoSharingApp 目录中操作。

    node index.js
    

    提示

    如果在使用 await 关键字时遇到错误,请确保已按照前面说明中的最后一步将 async 关键字添加到了 main 函数定义中。

祝贺

你已经掌握了使用适用于 JavaScript 的 Azure 存储 Blob 客户端库和 Azure Blob 存储的基本知识。 如果需要,可创建另一个容器,将更多图像上传到存储帐户或删除图像,进一步进行探索。 “适用于 JavaScript npm.js 的 Azure 存储 Blob 客户端库”页提供了许多说明该库用法的示例。