您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:使用 Azure 存储在云中上传图像数据Tutorial: Upload image data in the cloud with Azure Storage

本教程是一个系列中的第一部分。This tutorial is part one of a series. 在本教程中,你将了解如何部署一个 Web 应用,它使用 Azure 存储客户端库将图像上传到存储帐户。In this tutorial, you will learn how to deploy a web app that uses the Azure Storage Client Library to upload images to a storage account. 完成后,你将具有一个通过 Azure 存储来存储和显示图像的 Web 应用。When you're finished, you'll have a web app that stores and displays images from Azure storage.

在该系列的第一部分中,你会学习如何:In part one of the series, you learn how to:

  • 创建存储帐户Create a storage account
  • 创建容器并设置权限Create a container and set permissions
  • 检索访问密钥Retrieve an access key
  • 将 Web 应用部署到 AzureDeploy a web app to Azure
  • 配置应用设置Configure app settings
  • 与 Web 应用进行交互Interact with the web app

先决条件Prerequisites

需要一个 Azure 订阅才能完成此教程。To complete this tutorial, you need an Azure subscription. 在开始之前,创建一个免费帐户Create a free account before you begin.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 通过 Cloud Shell 可以将 bashPowerShell 与 Azure 服务配合使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To launch Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。 Select Try It in the upper-right corner of a code block. 选择“试用” 不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell” 按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. <a href="https://shell.azure.com" title="启动 Azure Cloud Shell
选择 Azure 门户右上方菜单栏中的“Cloud Shell” 按钮。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 启动 Cloud Shell。Launch Cloud Shell.
  2. 选择代码块上的“复制”按钮 以复制代码。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上使用 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上使用 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. Enter 运行此代码。Press Enter to run the code.

若要在本地安装并使用 CLI,本教程要求运行 Azure CLI 2.0.4 或更高版本。To install and use the CLI locally, this tutorial requires that you run the Azure CLI version 2.0.4 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如需进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install the Azure CLI.

创建资源组Create a resource group

使用 az group create 命令创建资源组。Create a resource group with the az group create command. Azure 资源组是在其中部署和管理 Azure 资源的逻辑容器。An Azure resource group is a logical container into which Azure resources are deployed and managed.

以下示例创建名为 myResourceGroup 的资源组。The following example creates a resource group named myResourceGroup.

az group create --name myResourceGroup --location southeastasia 

创建存储帐户Create a storage account

此示例将图像上传到 Azure 存储帐户中的 blob 容器。The sample uploads images to a blob container in an Azure Storage account. 存储帐户提供唯一的命名空间来存储和访问 Azure 存储数据对象。A storage account provides a unique namespace to store and access your Azure storage data objects. 使用 az storage account create 命令在创建的资源组中创建存储帐户。Create a storage account in the resource group you created by using the az storage account create command.

重要

在本教程的第 2 部分中,你将 Azure 事件网格与 Blob 存储配合使用。In part 2 of the tutorial, you use Azure Event Grid with Blob storage. 请确保在支持事件网格的 Azure 区域中创建你的存储帐户。Make sure to create your storage account in an Azure region that supports Event Grid. 有关受支持区域的列表,请参阅 Azure 产品(按区域)For a list of supported regions, see Azure products by region.

在以下命令中,请将 <blob_storage_account> 占位符替换为你自己的 Blob 存储帐户的全局唯一名称。In the following command, replace your own globally unique name for the Blob storage account where you see the <blob_storage_account> placeholder.

blobStorageAccount=<blob_storage_account>

az storage account create --name $blobStorageAccount \
--location southeastasia --resource-group myResourceGroup \
--sku Standard_LRS --kind blobstorage --access-tier hot 

创建 Blob 存储容器Create Blob storage containers

应用使用 Blob 存储帐户中的两个容器。The app uses two containers in the Blob storage account. 容器类似于文件夹,用于存储 blob。Containers are similar to folders and store blobs. images 容器是应用在其中上传完整分辨率图像的位置。The images container is where the app uploads full-resolution images. 在本系列的后面部分中,一个 Azure 函数应用将调整大小后的图像缩略图上传到 thumbnails 容器。In a later part of the series, an Azure function app uploads resized image thumbnails to the thumbnails container.

使用 az storage account keys list 命令获取存储帐户密钥。Get the storage account key by using the az storage account keys list command. 然后,使用此密钥通过 az storage container create 命令创建两个容器。Then, use this key to create two containers with the az storage container create command.

images 容器的公共访问权限设置为 offThe images container's public access is set to off. thumbnails 容器的公共访问权限设置为 containerThe thumbnails container's public access is set to container. container 公共访问权限设置允许访问网页的用户查看缩略图。The container public access setting permits users who visit the web page to view the thumbnails.

blobStorageAccountKey=$(az storage account keys list -g myResourceGroup \
-n $blobStorageAccount --query [0].value --output tsv)

az storage container create -n images --account-name $blobStorageAccount \
--account-key $blobStorageAccountKey --public-access off

az storage container create -n thumbnails --account-name $blobStorageAccount \
--account-key $blobStorageAccountKey --public-access container

echo "Make a note of your Blob storage account key..."
echo $blobStorageAccountKey

记下 Blob 存储帐户名称和密钥。Make a note of your Blob storage account name and key. 示例应用使用这些设置连接到存储帐户以上传图像。The sample app uses these settings to connect to the storage account to upload the images.

创建应用服务计划Create an App Service plan

应用服务计划指定托管应用的 Web 服务器场的位置、大小和功能。An App Service plan specifies the location, size, and features of the web server farm that hosts your app.

使用 az appservice plan create 命令创建应用服务计划。Create an App Service plan with the az appservice plan create command.

以下示例在免费 定价层中创建名为 myAppServicePlan 的应用服务计划:The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku Free

创建 Web 应用Create a web app

Web 应用为从 GitHub 示例存储库部署的示例应用代码提供承载空间。The web app provides a hosting space for the sample app code that's deployed from the GitHub sample repository. 使用 az webapp create 命令在 myAppServicePlan 应用服务计划中创建 Web 应用Create a web app in the myAppServicePlan App Service plan with the az webapp create command.

在以下命令中,将 <web_app> 替换为唯一名称。In the following command, replace <web_app> with a unique name. 有效的字符是 a-z0-9-Valid characters are a-z, 0-9, and -. 如果 <web_app> 不唯一,将收到错误消息:具有给定名称 <web_app> 的网站已存在。If <web_app> is not unique, you get the error message: Website with given name <web_app> already exists. Web 应用的默认 URL 为 https://<web_app>.azurewebsites.netThe default URL of the web app is https://<web_app>.azurewebsites.net.

webapp=<web_app>

az webapp create --name $webapp --resource-group myResourceGroup --plan myAppServicePlan

从 GitHub 存储库部署示例应用Deploy the sample app from the GitHub repository

应用服务支持通过多种方式将内容部署到 Web 应用。App Service supports several ways to deploy content to a web app. 在本教程中,将从公共 GitHub 示例存储库部署 Web 应用。In this tutorial, you deploy the web app from a public GitHub sample repository. 使用 az webapp deployment source config 命令配置 Web 应用的 GitHub 部署。Configure GitHub deployment to the web app with the az webapp deployment source config command.

示例项目包含一个 ASP.NET MVC 应用。The sample project contains an ASP.NET MVC app. 该应用接受一个图像,将其保存到存储帐户,然后从缩略图容器显示图像。The app accepts an image, saves it to a storage account, and displays images from a thumbnail container. Web 应用使用 Azure 存储客户端库中的 Microsoft.Azure.StorageMicrosoft.Azure.Storage.Blob 和 Microsoft.Azure.Storage.Auth 命名空间与 Azure 存储进行交互。The web app uses the Microsoft.Azure.Storage, Microsoft.Azure.Storage.Blob, and the Microsoft.Azure.Storage.Auth namespaces from the Azure Storage client library to interact with Azure storage.

az webapp deployment source config --name $webapp \
--resource-group myResourceGroup --branch master --manual-integration \
--repo-url https://github.com/Azure-Samples/storage-blob-upload-from-webapp

配置 Web 应用设置Configure web app settings

示例 Web 应用使用 Azure 存储客户端库请求用于上传图像的访问令牌。The sample web app uses the Azure Storage Client Library to request access tokens, which are used to upload images. 存储 SDK 使用的存储帐户凭据是在 Web 应用的应用设置中设置的。The storage account credentials used by the Storage SDK are set in the app settings for the web app. 使用 az webapp config appsettings set 命令将应用设置添加到已部署的应用。Add app settings to the deployed app with the az webapp config appsettings set command.

az webapp config appsettings set --name $webapp --resource-group myResourceGroup \
--settings AzureStorageConfig__AccountName=$blobStorageAccount \
AzureStorageConfig__ImageContainer=images  \
AzureStorageConfig__ThumbnailContainer=thumbnails \
AzureStorageConfig__AccountKey=$blobStorageAccountKey  

在部署并配置 Web 应用后,你可以在应用中测试图像上传功能。After you deploy and configure the web app, you can test the image upload functionality in the app.

上传图像Upload an image

若要测试 Web 应用,请浏览到已发布应用的 URL。To test the web app, browse to the URL of your published app. Web 应用的默认 URL 为 https://<web_app>.azurewebsites.netThe default URL of the web app is https://<web_app>.azurewebsites.net.

选择“上传照片” 区域以选择并上传文件,或者将文件拖放到该区域上。Select the Upload photos region to select and upload a file, or drag a file onto the region. 如果成功上传,图像会消失。The image disappears if successfully uploaded. “生成的缩略图” 部分将保持为空,直到我们稍后在本主题中对其进行测试为止。The Generated Thumbnails section will remain empty until we test it later in this topic.

在 .NET 中上传照片

在示例代码中,Storagehelper.cs 文件中的 UploadFiletoStorage 任务用于通过 UploadFromStreamAsync 方法将图像上传到存储帐户中的 images 容器。In the sample code, the UploadFiletoStorage task in the Storagehelper.cs file is used to upload the images to the images container within the storage account using the UploadFromStreamAsync method. 下面的代码示例包含 UploadFiletoStorage 任务。The following code sample contains the UploadFiletoStorage task.

public static async Task<bool> UploadFileToStorage(Stream fileStream, string fileName, AzureStorageConfig _storageConfig)
{
    // Create storagecredentials object by reading the values from the configuration (appsettings.json)
    StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

    // Create cloudstorage account by passing the storagecredentials
    CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
    CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);

    // Get the reference to the block blob from the container
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

    // Upload the file
    await blockBlob.UploadFromStreamAsync(fileStream);

    return await Task.FromResult(true);
}

以下是用于前一任务的类和方法:The following classes and methods are used in the preceding task:

Class 方法Method
StorageCredentialsStorageCredentials
CloudStorageAccountCloudStorageAccount CreateCloudBlobClientCreateCloudBlobClient
CloudBlobClientCloudBlobClient GetContainerReferenceGetContainerReference
CloudBlobContainerCloudBlobContainer GetBlockBlobReferenceGetBlockBlobReference
CloudBlockBlobCloudBlockBlob UploadFromStreamAsyncUploadFromStreamAsync

验证图像是否显示在存储帐户中Verify the image is shown in the storage account

登录到 Azure 门户Sign in to the Azure portal. 从左侧菜单中,选择“存储帐户” ,然后选择你的存储帐户的名称。From the left menu, select Storage accounts, then select the name of your storage account. 在“Blob 服务” 下,选择“Blob” ,然后选择“images” 容器。Under Blob Service, select Blobs, then select the images container.

验证图像是否显示在该容器中。Verify the image is shown in the container.

Azure 门户图像容器列表

测试缩略图查看Test thumbnail viewing

为了测试缩略图查看,你将把图像上传到 thumbnails 容器,以检查应用可以读取 thumbnails 容器。To test thumbnail viewing, you'll upload an image to the thumbnails container to check whether the app can read the thumbnails container.

登录到 Azure 门户Sign in to the Azure portal. 从左侧菜单中,选择“存储帐户” ,然后选择你的存储帐户的名称。From the left menu, select Storage accounts, then select the name of your storage account. 在“Blob 服务” 下,选择“Blob” ,然后选择“thumbnails” 容器。Under Blob Service, select Blobs, then select the thumbnails container. 选择“上传” 以打开“上传 blob” 窗格。Select Upload to open the Upload blob pane.

使用文件选取器选择文件,然后选择“上传” 。Choose a file with the file picker and select Upload.

导航回到应用,以验证上传到 thumbnails 容器的图像是否可见。Navigate back to your app to verify that the image uploaded to the thumbnails container is visible.

在本系列的第二部分中,您将使缩略图创建自动化,以便不需要此图像。In part two of the series, you automate thumbnail image creation so you don't need this image. 在 Azure 门户中的 thumbnails 容器中,选择上传的图像,然后选择“删除” 以删除图像。In the thumbnails container in the Azure portal, select the image you uploaded and select Delete to delete the image.

你可以启用 CDN 来缓存 Azure 存储帐户的内容。You can enable CDN to cache content from your Azure storage account. 有关如何对 Azure 存储帐户启用 CDN 的详细信息,请参阅:将 Azure 存储帐户与 Azure CDN 集成For more information about how to enable CDN with your Azure storage account, see Integrate an Azure storage account with Azure CDN.

后续步骤Next steps

在本系列的第一部分中,你已学习了如何配置 Web 应用来与存储进行交互。In part one of the series, you learned how to configure a web app to interact with storage.

请前进到本系列的第二部分,以了解如何使用事件网格触发 Azure 函数以调整图像大小。Go on to part two of the series to learn about using Event Grid to trigger an Azure function to resize an image.