Lun*_*Dev 5 c# azure azure-storage azure-storage-blobs azure-blob-storage
我试图通过 Azure Blob 存储中的 URL 检索图像,但没有找到它,这是我得到的:
我的代码如下:
public async Task<bool> UploadFileAsync(string containerReference, string blobReference, string route)
{
CloudBlobContainer container = blobClient.GetContainerReference(containerReference);
container.CreateIfNotExists();
CloudBlockBlob blob = container.GetBlockBlobReference(blobReference);
try
{
using (var fileStream = System.IO.File.OpenRead(route))
{
await blob.UploadFromStreamAsync(fileStream);
}
}
catch (System.Exception)
{
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
它成功地将文件上传到 blob:
然后我尝试检索其 URL 以直接访问它:
public string GetBlobUrl(string containerReference, string blobReference)
{
CloudBlobContainer container = blobClient.GetContainerReference(containerReference);
CloudBlockBlob blob = container.GetBlockBlobReference(blobReference);
return blob.Uri.ToString();
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
默认情况下,容器及其 Blob 只能由存储帐户所有者访问。如果您希望匿名请求可以读取私有容器中的 blob,您可以授予 blob 的公共读取访问权限。此外,正如 David Makogon 在评论中提到的,您还可以通过共享访问签名授予对私有 blob 的临时公共访问权限。
CloudBlobContainer container = cloudBlobClient.GetContainerReference("mycontainer");
CloudBlockBlob blob = container.GetBlockBlobReference("testimg.PNG");
SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5);
sasConstraints.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddDays(7);
sasConstraints.Permissions = SharedAccessBlobPermissions.Read;
string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);
string URL = blob.Uri + sasBlobToken;
Run Code Online (Sandbox Code Playgroud)