【问题标题】:How to download an Azure Storage blob as a local file using PHP?如何使用 PHP 将 Azure 存储 blob 下载为本地文件?
【发布时间】:2014-10-28 09:59:02
【问题描述】:
我想使用 Azure 存储中的文件名下载 Azure 存储 blob 并将其保存为本地计算机上的文件。我在名为 download.php 的文件中使用此处 (tutorial link) 中的步骤,当我转到 download.php 时,我可以在浏览器中看到文件内容。如果我在 index.php 中添加一个指向 download.php 的链接,我可以右键单击该链接并“另存为”,然后将文件另存为 myfile.doc。然后我可以成功打开 myfile.doc。
index.php:
echo '<a href="http://myserver/dev/download.php" >Click me</a>';
但是...
我想知道的是如何在无需用户右键单击的情况下将链接“另存为”。另外,我有文件名(来自 Azure 存储)——但我不知道如何使用该文件名获取要保存的文件。当用户单击链接时,如何获取文件以文件名保存到用户的下载目录?
【问题讨论】:
标签:
php
azure
azure-storage
azure-blob-storage
【解决方案1】:
为此,我将 index.php 更改为一个表单:
echo '<form method="post" action="download.php"><div id="divexport">';
echo '<input type="hidden" name="Export" value="coverLetter">';
echo '<input type="submit" id="Export" value="Cover Letter" />';
echo '</div></form>';
然后将头信息添加到download.php,就在fpassthru之前
// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$blobfile = "myblob.pdf";
$filename = basename($blobfile);
$ext = new SplFileInfo($filename);
$fileext = strtolower($ext->getExtension());
try {
// Get blob.
$blob = $blobRestProxy->getBlob("document", $blobfile);
if($fileext === "pdf") {
header('Content-type: application/pdf');
} else if ($fileext === "doc") {
header('Content-type: application/msword');
} else if ($fileext === "docx") {
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
} else if($fileext === "txt") {
header('Content-type: plain/text');
}
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
fpassthru($blob->getContentStream());
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}