使用 PHP 的 Azure 文件存储

Azure File Storage using PHP

我想要 运行 单个网页来显示存储在 Azure 文件存储中的文件。它必须是 Azure 文件存储,因为这些文件来自 Docker 容器,该容器已安装到该文件存储。

我有一个 Azure 容器实例 在 Azure 文件存储中存储 PDF 文件。现在我 运行 一个可以读取所有 PDF 的 WebApp (PHP)。

我已经安装了 Microsoft Azure 存储文件 PHP SDK,但不知道如何使用它。即使是 sample.php 也没有帮助我挺身而出。如果有人能帮我简单地狙击一下,那将非常有帮助。

我看到您想在网页中直接显示 Azure 文件存储中的 PDF 文件。通常,最佳做法是使用 Azure 文件存储中文件的 sas 令牌生成 url。

所以我按照 GitHub 存储库 Azure/azure-storage-php 在我的示例项目中为 PHP 安装了 Azure 文件存储 SDK,这是我的示例代码及其依赖项。

我的示例项目的文件结构如下图。

我的composer.json文件内容如下。

{
  "require": {
    "microsoft/azure-storage-file": "*"
  }
}

我的示例 PHP 文件 demo.php 如下,这是受官方示例 azure-storage-php/samples/FileSamples.php.

的函数 generateFileDownloadLinkWithSAS 的启发
<?php
require_once "vendor/autoload.php"; 
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\File\FileSharedAccessSignatureHelper;

$accountName = "<your account name>";
$accountKey = "<your account key>";

$shareName = "<your share name>";
$fileName = "<your pdf file name>";

$now = date(DATE_ISO8601);
$date = date_create($now);
date_add($date, date_interval_create_from_date_string("1 hour"));
$expiry = str_replace("+0000", "Z", date_format($date, DATE_ISO8601));

$helper = new FileSharedAccessSignatureHelper($accountName, $accountKey);
$sas = $helper->generateFileServiceSharedAccessSignatureToken(
        Resources::RESOURCE_TYPE_FILE,
        "$shareName/$fileName",
        'r',                        // Read
        $expiry // A valid ISO 8601 format expiry time, such as '2020-01-01T08:30:00Z' 
    );
$fileUrlWithSAS = "https://$accountName.file.core.windows.net/$shareName/$fileName?$sas";
echo "<h1>Demo to display PDF from Azure File Storage</h1>";
echo "<iframe src='$fileUrlWithSAS'  width='800' height='500' allowfullscreen webkitallowfullscreen></iframe>";
?>

我的网页在Chrome和Firefox中的结果如下图。

Chrome中的结果:

Firefox 中的结果:


更新:列出文件共享中文件的代码,如下所示。

<?php
require_once "vendor/autoload.php"; 
use MicrosoftAzure\Storage\File\FileRestProxy;

$accountName = "<your account name>";
$accountKey = "<your account key>";

$shareName = "<your share name>";

$connectionString = "DefaultEndpointsProtocol=https;AccountName=$accountName;AccountKey=$accountKey";
$fileClient = FileRestProxy::createFileService($connectionString);

$list = $fileClient->listDirectoriesAndFiles($shareName);

function endsWith( $str, $sub ) {
    return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}

foreach($list->getFiles() as &$file) {
    $fileName = $file->getName();
    if(endsWith($fileName, ".pdf")) {
        echo $fileName."\n";
    }
};
?>