PHP blob存文件,Azure 快速入门 - 使用 PHP 在对象存储中创建 blob | Microsoft Docs

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

使用 PHP 将对象转移到 Azure Blob 存储或从 Azure Blob 存储转移对象Transfer objects to/from Azure Blob storage using PHP

11/14/2018

本文内容

本快速入门介绍如何使用 PHP 上传、下载和列出 Azure Blob 存储的容器中的块 Blob。In this quickstart, you learn how to use PHP 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 free account 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

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

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

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

此命令会将存储库克隆到本地 git 文件夹。This command clones the repository to your local git folder. 若要打开 PHP 示例应用程序,请查找 storage-blobs-php-quickstart 文件夹,然后打开 phpqs.php 文件。To open the PHP sample application, look for the storage-blobs-php-quickstart folder, and open the phpqs.php 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:

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

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

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

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

9bddced5a57e4d5d74049abbffce680e.png

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

在应用程序中,必须提供存储帐户名称和帐户密钥,以创建应用程序的 BlobRestProxy 实例。In the application, you must provide your storage account name and account key to create the BlobRestProxy instance for your application. 建议将这些标识符存储在运行应用程序的本地计算机的环境变量中。It is recommended to store these identifiers within an environment variable on the local machine running the application. 根据操作系统按照下面的一个示例创建环境变量。Use one of the following examples depending on your Operating System to create the environment variable. 将 youraccountname 和 youraccountkey 值分别替换为帐户名称和密钥。Replace the youraccountname and youraccountkey values with your account name and key.

export ACCOUNT_NAME=

export ACCOUNT_KEY=

setx ACCOUNT_NAME=

setx ACCOUNT_KEY=

配置环境Configure your environment

从本地 git 文件夹中获取此文件夹,将其置于 PHP 服务器提供的目录中。Take the folder from your local git folder and place it in a directory served by your PHP server. 然后,打开作用域为该目录的命令提示符并输入:php composer.phar installThen, open a command prompt scoped to that same directory and enter: php composer.phar install

运行示例Run the sample

此示例在“.”文件夹中创建一个测试文件。This sample creates a test file in the '.' 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:

Uploading BlockBlob: HelloWorld.txt

These are the blobs present in the container: HelloWorld.txt: https://myexamplesacct.blob.core.windows.net/blockblobsleqvxd/HelloWorld.txt

This is the content of the blob uploaded: Hello Azure!

按显示的键时,示例程序会删除存储容器和文件。When you press the button displayed, the sample program deletes the storage container and the files. 继续前,请在服务器的文件夹中查看这两个文件。Before you continue, check your server's 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 存储 BlobRestProxy 对象的实例,用于设置连接凭据。Create an instance of the Azure storage BlobRestProxy object to set up connection credentials.

创建 BlobService 对象,使之指向存储帐户中的 Blob 服务。Create the BlobService object that points to the Blob service in your storage account.

创建 容器 对象,让其代表要访问的容器。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.

有了云 blobClient 容器对象后,可以创建 块 Blob 对象,使之指向你感兴趣的特定 Blob,Once you have the blobClient container object, you can create the Block blob object that points to the specific blob in which you are interested. 然后执行上传、下载、复制等操作。Then you can 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 set permissions on the container so the blobs are public. 容器名称为 quickstartblobs。The container is called quickstartblobs.

# Setup a specific instance of an Azure::Storage::Client

$connectionString = "DefaultEndpointsProtocol=https;AccountName=".getenv('account_name').";AccountKey=".getenv('account_key');

// Create blob client.

$blobClient = BlobRestProxy::createBlobService($connectionString);

# Create the BlobService that represents the Blob service for the storage account

$createContainerOptions = new CreateContainerOptions();

$createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);

// Set container metadata.

$createContainerOptions->addMetaData("key1", "value1");

$createContainerOptions->addMetaData("key2", "value2");

$containerName = "blockblobs".generateRandomString();

try {

// Create container.

$blobClient->createContainer($containerName, $createContainerOptions);

将 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. 然后可以使用 createBlockBlob() 方法将文件上传到指定的路径。You can then upload the file to the specified path using the createBlockBlob() method.

示例代码使用一个本地文件并将其上传到 Azure。The sample code takes a local file and uploads it to Azure. 在代码中,该文件存储为 myfile,Blob 的名称存储为 fileToUpload。The file is stored as myfile and the name of the blob as fileToUpload in the code. 以下示例将文件上传到名为“quickstartblobs”的容器。The following example uploads the file to your container called quickstartblobs.

$myfile = fopen("HelloWorld.txt", "w") or die("Unable to open file!");

fclose($myfile);

# Upload file as a block blob

echo "Uploading BlockBlob: ".PHP_EOL;

echo $fileToUpload;

echo "
";

$content = fopen($fileToUpload, "r");

//Upload blob

$blobClient->createBlockBlob($containerName, $fileToUpload, $content);

若要对块 Blob 进行部分更新,请使用 createblocklist() 方法。To perform a partial update of the content of a block blob, use the createblocklist() 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

可以使用 listBlobs() 方法获取容器中文件的列表。You can get a list of files in the container using the listBlobs() 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.

$listBlobsOptions = new ListBlobsOptions();

$listBlobsOptions->setPrefix("HelloWorld");

echo "These are the blobs present in the container: ";

do{

$result = $blobClient->listBlobs($containerName, $listBlobsOptions);

foreach ($result->getBlobs() as $blob)

{

echo $blob->getName().": ".$blob->getUrl()."
";

}

$listBlobsOptions->setContinuationToken($result->getContinuationToken());

} while($result->getContinuationToken());

获取 Blob 的内容Get the content of your blobs

使用 getBlob() 方法获取 Blob 的内容Get the contents of your blobs using the getBlob() method. 以下代码显示在前面部分上传的 Blob 的内容。The following code displays the contents of the blob uploaded in a previous section.

$blob = $blobClient->getBlob($containerName, $fileToUpload);

fpassthru($blob->getContentStream());

清理资源Clean up resources

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

// Delete blob.

echo "Deleting Blob".PHP_EOL;

echo $fileToUpload;

echo "
";

$blobClient->deleteBlob($_GET["containerName"], $fileToUpload);

// Delete container.

echo "Deleting Container".PHP_EOL;

echo $_GET["containerName"].PHP_EOL;

echo "
";

$blobClient->deleteContainer($_GET["containerName"]);

//Deleting local file

echo "Deleting file".PHP_EOL;

echo "
";

unlink($fileToUpload);

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

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

在 GitHub 上查看、下载并安装 Azure 存储的 PHP 客户端库源代码。View, download, and install the PHP client library source code for Azure Storage on GitHub.

浏览使用 PHP 客户端库编写的 Blob 存储示例。Explore Blob storage samples written using the PHP client library.

后续步骤Next steps

本快速入门介绍了如何使用 PHP 在本地磁盘和 Azure Blob 存储之间转移文件。In this quickstart, you learned how to transfer files between a local disk and Azure blob storage using PHP. 若要详细了解 PHP 的用法,请转到 PHP 开发人员中心。To learn more about working with PHP, continue to our PHP Developer center.

For more information about the Storage Explorer and Blobs, see Manage Azure Blob storage resources with Storage Explorer.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值