如何使用PHP将Azure存储blob下载为本地文件?
问题描述:
我想使用Azure存储中的文件名将本地计算机上的Azure存储块作为文件下载并保存。我在这里使用了一个名为download.php的文件(tutorial link),当我去download.php时,我可以在浏览器中看到文件内容。如果我然后把index.php中的链接放到download.php中,我可以右键单击链接并“另存为”,并将文件另存为myfile.doc。然后我可以成功打开myfile.doc。如何使用PHP将Azure存储blob下载为本地文件?
的index.php:
echo '<a href="http://myserver/dev/download.php" >Click me</a>';
不过...... 我想知道的是如何得到的链接“另存为”,而不必点击右键用户。此外,我有文件名(来自Azure存储) - 但我不知道如何使用该文件名来保存文件。当用户点击链接时,如何使用文件名将文件保存到用户的下载目录?
答
要做到这一点,我改变的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 />";
}