快速入门:使用 Ruby 上传、下载和列出 BlobQuickstart: Upload, download, and list blobs using Ruby

本快速入门介绍如何使用 Ruby 上传、下载和列出 Azure Blob 存储的容器中的块 Blob。In this quickstart, you learn how to use Ruby to upload, download, and list block blobs in a container in Azure Blob storage.

必备条件Prerequisites

若要访问 Azure 存储,需要一个 Azure 订阅。To access Azure Storage, you'll need an Azure subscription. 如果还没有订阅,请在开始前创建一个试用版订阅If you don't already have a subscription, create a Trial Subscription before you begin.

对 Azure 存储进行的所有访问都要通过存储帐户完成。All access to Azure Storage takes place through a storage account. 对于本快速入门,请使用 Azure 门户、Azure PowerShell 或 Azure CLI 创建存储帐户。For this quickstart, create a storage account using the Azure portal, Azure PowerShell, or Azure CLI. 有关如何创建存储帐户的帮助,请参阅创建存储帐户For help creating a storage account, see Create a storage account.

请确保已安装下述额外的必备组件:Make sure you have the following additional prerequisites installed:

下载示例应用程序Download the sample application

本快速入门中使用的示例应用程序是基本的 Ruby 应用程序。The sample application used in this quickstart is a basic Ruby application.

使用 git 可将应用程序的副本下载到开发环境。Use git to download a copy of the application to your development environment.

git clone https://github.com/Azure-Samples/storage-blobs-ruby-quickstart.git 

此命令会将存储库克隆到本地 git 文件夹。This command clones the repository to your local git folder. 若要打开 Ruby 示例应用程序,请查找 storage-blobs-ruby-quickstart 文件夹,然后打开 example.rb 文件。To open the Ruby sample application, look for the storage-blobs-ruby-quickstart folder, and open the example.rb file.

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

此示例应用程序需要对存储帐户访问进行授权。The sample application needs to authorize access to your storage account. 以连接字符串形式将存储帐户凭据提供给应用程序。Provide your storage account credentials to the application in the form of a connection string. 若要查看存储帐户凭据,请执行以下操作:To view your storage account credentials:

  1. Azure 门户中转到自己的存储帐户。In to the Azure portal go to your storage account.

  2. 在存储帐户概述的“设置” 部分中,选择“访问密钥” 以显示你的帐户访问密钥和连接字符串。In the Settings section of the storage account overview, select Access keys to display your account access keys and connection string.

  3. 请记下存储帐户的名称,进行授权时,需提供该名称。Note the name of your storage account, which you'll need for authorization.

  4. 找到“key1”下面的“密钥”值,选择“复制”复制该帐户密钥。 Find the Key value under key1, and select Copy to copy the account key.

    显示如何从 Azure 门户复制帐户密钥的屏幕截图

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

在应用程序中,必须提供存储帐户名称和帐户密钥,以创建应用程序的 BlobService 实例。In the application, you must provide your storage account name and account key to create the BlobService instance for your application. 从 IDE 中的解决方案资源管理器打开 example.rb 文件。Open the example.rb file from the Solution Explorer in your IDE. 将 accountname 和 accountkey 值分别替换为帐户名称和密钥。Replace the accountname and accountkey values with your account name and key.

blob_client = Azure::Storage::Blob::BlobService.create(
            storage_account_name: account_name,
            storage_access_key: account_key,
        storage_dns_suffix: "core.chinacloudapi.cn"
          )

运行示例Run the sample

此示例将在“文档”文件夹中创建一个测试文件。This sample creates a test file in the 'Documents' folder. 示例程序会将该测试文件上传到 Blob 存储,列出容器中的 blob,并使用新名称下载此文件。The sample program uploads the test file to Blob storage, lists the blobs in the container, and downloads the file with a new name.

运行该示例。Run the sample. 以下输出是运行应用程序时返回的输出的示例:The following output is an example of the output returned when running the application:

Creating a container: quickstartblobs7b278be3-a0dd-438b-b9cc-473401f0c0e8

Temp file = C:\Users\azureuser\Documents\QuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078.txt

Uploading to Blob storage as blobQuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078.txt

List blobs in the container
         Blob name: QuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078.txt

Downloading blob to C:\Users\azureuser\Documents\QuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078_DOWNLOADED.txt

按任意键继续时,示例程序会删除存储容器和文件。When you press any key to continue, the sample program deletes the storage container and the files. 继续前,请在“文档”文件夹中查看这两个文件。Before you continue, check your 'Documents' folder for the two files. 可以打开它们,并看到它们完全相同。You can open them and see they are identical.

还可以使用工具(如 Azure 存储资源管理器)查看 Blob 存储中的文件。You can also use a tool such as the Azure Storage Explorer to view the files in Blob storage. Azure 存储资源管理器是免费的跨平台工具,可用于访问存储帐户信息。Azure Storage Explorer is a free cross-platform tool that allows you to access your storage account information.

验证文件后,按任意键可完成演示并删除测试文件。After you've verified the files, hit any key to finish the demo and delete the test files. 了解此示例的用途以后,即可打开 example.rb 文件来查看代码。Now that you know what the sample does, open the example.rb file to look at the code.

了解示例代码Understand the sample code

接下来逐步介绍示例代码,以便展示其工作方式。Next, we walk through the sample code so that you can understand how it works.

获取对存储对象的引用Get references to the storage objects

首先创建对用于访问和管理 Blob 存储的对象的引用。The first thing to do is create the references to the objects used to access and manage Blob storage. 这些对象相互关联,并且每个对象被列表中的下一个对象使用。These objects build on each other, and each is used by the next one in the list.

  • 创建 Azure 存储 BlobService 对象的实例,用于设置连接凭据。Create an instance of the Azure storage BlobService object to set up connection credentials.
  • 创建容器对象,让其代表要访问的容器。Create the Container object, which represents the container you are accessing. 容器用于组织 blob,就像使用计算机上的文件夹组织文件一样。Containers are used to organize your blobs like you use folders on your computer to organize your files.

有了云 Blob 容器后,可以创建 Blob 对象,使之指向你感兴趣的特定 Blob,然后执行上传、下载、复制等操作。Once you have the Cloud Blob container, you can create the Block blob object that points to the specific blob in which you are interested, and perform operations such as upload, download, and copy.

重要

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

此部分设置 Azure 存储客户端的实例,实例化 Blob 服务对象,创建新的容器,然后设置容器的权限,使 Blob 公开。In this section, you set up an instance of Azure storage client, instantiate the blob service object, create a new container, and then set permissions on the container so the blobs are public. 容器名称为 quickstartblobs 。The container is called quickstartblobs.

# Create a BlobService object
blob_client = Azure::Storage::Blob::BlobService.create(
    storage_account_name: account_name,
    storage_access_key: account_key,
    storage_dns_suffix: "core.chinacloudapi.cn"
    )

# Create a container called 'quickstartblobs'.
container_name ='quickstartblobs' + SecureRandom.uuid
container = blob_client.create_container(container_name)   

# Set the permission so the blobs are public.
blob_client.set_container_acl(container_name, "container")

将 blob 上传到容器Upload blobs to the container

Blob 存储支持块 blob、追加 blob 和页 blob。Blob storage supports block blobs, append blobs, and page blobs. 块 blob 是最常用的 blob,此快速入门中使用的便是它。Block blobs are the most commonly used, and that is what is used in this quickstart.

若要将文件上传到 blob,请通过将本地驱动器上的目录名称和文件名称联接在一起来获取文件的完整路径。To upload a file to a blob, get the full path of the file by joining the directory name and the file name on your local drive. 然后可以使用 create_block_blob() 方法将文件上传到指定的路径。You can then upload the file to the specified path using the create_block_blob() method.

示例代码将创建一个本地文件,以供上传和下载,并将要上传的此文件存储为 filepath_to_file_ ,将 blob 的名称存储为 localfile_name_The sample code creates a local file to be used for the upload and download, storing the file to be uploaded as file_path_to_file and the name of the blob as local_file_name. 以下示例将文件上传到名为“quickstartblobs”的容器 。The following example uploads the file to your container called quickstartblobs.

# Create a file in Documents to test the upload and download.
local_path=File.expand_path("~/Documents")
local_file_name ="QuickStart_" + SecureRandom.uuid + ".txt"
full_path_to_file =File.join(local_path, local_file_name)

# Write text to the file.
file = File.open(full_path_to_file,  'w')
file.write("Hello, World!")
file.close()

puts "Temp file = " + full_path_to_file
puts "\nUploading to Blob storage as blob" + local_file_name

# Upload the created file, using local_file_name for the blob name
blob_client.create_block_blob(container.name, local_file_name, full_path_to_file)

若要对块 Blob 进行部分更新,请使用 create_block_list() 方法。To perform a partial update of the content of a block blob, use the create_block_list() method. 块 blob 最大可以为 4.7 TB,并且可以是从 Excel 电子表格到大视频文件的任何内容。Block blobs can be as large as 4.7 TB, and can be anything from Excel spreadsheets to large video files. 页 blob 主要用于用于备份 IaaS VM 的 VHD 文件。Page blobs are primarily used for the VHD files used to back IaaS VMs. 追加 blob 用于日志记录,例如有时需要写入到文件,再继续添加更多信息。Append blobs are used for logging, such as when you want to write to a file and then keep adding more information. 追加 Blob 应在单编写器模型中使用。Append blob should be used in a single writer model. 存储在 Blob 存储中的大多数对象都是块 blob。Most objects stored in Blob storage are block blobs.

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

可以使用 list_blobs() 方法获取容器中文件的列表。You can get a list of files in the container using the list_blobs() method. 下面的代码检索 blob 列表,然后循环访问它们,显示在容器中找到的 blob 的名称。The following code retrieves the list of blobs, then loops through them, showing the names of the blobs found in a container.

# List the blobs in the container
nextMarker = nil
loop do
    blobs = blob_client.list_blobs(container_name, { marker: nextMarker })
    blobs.each do |blob|
        puts "\tBlob name #{blob.name}"
    end
    nextMarker = blobs.continuation_token
    break unless nextMarker && !nextMarker.empty?
end

下载 BlobDownload the blobs

使用 get_blob() 方法将 Blob 下载到本地磁盘。Download blobs to your local disk using the get_blob() method. 以下代码将下载前面部分所上传的 blob。The following code downloads the blob uploaded in a previous section. 会将“_DOWNLOADED”添加为 blob 名称的前缀,以便可以在本地磁盘上同时看到这两个文件。"_DOWNLOADED" is added as a suffix to the blob name so you can see both files on local disk.

# Download the blob(s).
# Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents.
full_path_to_file2 = File.join(local_path, local_file_name.gsub('.txt', '_DOWNLOADED.txt'))

puts "\n Downloading blob to " + full_path_to_file2
blob, content = blob_client.get_blob(container_name,local_file_name)
File.open(full_path_to_file2,"wb") {|f| f.write(content)}

清理资源Clean up resources

如果不再需要本快速入门中上传的 Blob,可使用 delete_container() 方法删除整个容器。If you no longer need the blobs uploaded in this quickstart, you can delete the entire container using the delete_container() method. 如果不再需要已创建的文件,请使用 delete_blob() 方法将文件删除。If the files created are no longer needed, you use the delete_blob() method to delete the files.

# Clean up resources. This includes the container and the temp files
blob_client.delete_container(container_name)
File.delete(full_path_to_file)
File.delete(full_path_to_file2)    

用于开发包含 Blob 的 Ruby 应用程序的资源Resources for developing Ruby applications with blobs

查看以下附加资源,了解如何使用 Blob 存储进行 Ruby 开发:See these additional resources for Ruby development with Blob storage:

后续步骤Next steps

本快速入门介绍了如何使用 Ruby 在本地磁盘和 Azure Blob 存储之间转移文件。In this quickstart, you learned how to transfer files between a local disk and Azure blob storage using Ruby. 要深入了解如何使用 Blob 存储,请继续学习 Blob 存储操作说明。To learn more about working with blob storage, continue to the Blob storage How-to.

若要详细了解存储资源管理器和 Blob,请参阅使用存储资源管理器管理 Azure Blob 存储资源For more information about the Storage Explorer and Blobs, see Manage Azure Blob storage resources with Storage Explorer.