【问题标题】:Simple PHP cURL method for downloading file from Azure storage blob用于从 Azure 存储 blob 下载文件的简单 PHP cURL 方法
【发布时间】:2021-03-07 13:48:33
【问题描述】:

我正在将文件从本地服务器上传到 Azure 存储 - 使用简单 PHP cURL 函数的 blob 容器。我从以下网址获取代码。

https://stackoverflow.com/questions/41682393/simple-php-curl-file-upload-to-azure-storage-blob

谁能告诉我任何可以从 Azure 存储下载文件的链接或代码 - 没有任何 SDK 和/或多个文件/库的 blob。应该是上传功能吧。

提前致谢!

【问题讨论】:

  • 示例使用Put Blob API 上传blob。您可以尝试Get Blob API 下载。
  • @PamelaPeng 谢谢。我阅读了文档,但不明白如何将 GET Blob Api 与 php 代码集成。

标签: php azure curl azure-storage azure-storage-files


【解决方案1】:

这是我提到的sample。非常详细,可以帮助您理解使用 cURL 请求 API,例如 Get Blob API

请求:

GET https://myaccount.blob.core.windows.net/mycontainer/myblob
  x-ms-date: Mon, 24 Apr 2021 06:34:09 GMT
  x-ms-version: 2014-02-14
  Authorization: SharedKey myaccount:<signature_str>

你可以参考这个。

<?php

$storageAccount = '';
$containerName = '';
$blobName = '';
$account_key = '';

$date = gmdate('D, d M Y H:i:s \G\M\T');
$version = "2019-12-12";

$stringtosign = "GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:". $date . "\nx-ms-version:".$version."\n/".$storageAccount."/".$containerName."/".$blobName;
$signature = 'SharedKey'.' '.$storageAccount.':'.base64_encode(hash_hmac('sha256', $stringtosign, base64_decode($account_key), true));
echo "\n\n" . $signature;

$header = array (
    "x-ms-date: " . $date,       
    "x-ms-version: " . $version,       
    "Authorization: " . $signature
);

$url="https://$storageAccount.blob.core.windows.net/$containerName/$blobName";
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
curl_exec ( $ch );
$result = curl_exec($ch);
echo "\n\n" . $result;

if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
}

file_put_contents('D://demo//downloaded.txt', $result); // save the string to a file

curl_close($ch);

【讨论】:

  • 谢谢。这个答案是我一直在寻找的。但是运行此代码后,我的下载文件夹中得到了 0kb 文件,相关软件不支持打开。
  • 嗨,@Martin!我用经过测试的代码编辑我的回复。它有效。
猜你喜欢
  • 2017-05-31
  • 2015-06-20
  • 2021-12-08
  • 2019-09-05
  • 2020-08-08
  • 2020-01-01
  • 2021-07-15
相关资源
最近更新 更多