我已将一些jpg和txt文件上传到azure blob商店,我已阅读this tutorial,所以我知道如何检索它们。
我想弄清楚的是当点击我的cshtml页面中的链接时如何加载和链接到文件。
谢谢!
答案 0 :(得分:9)
如果你知道如何检索你知道如何加载它们的文件,你可以设置一些非常简单的东西。
ViewModel,它将代表您要在视图/页面上显示的数据。
public class FileViewModel
{
public string FileName {get; set;}
public string AzureUrl {get; set;}
}
控制器操作
public ActionResult ListFiles()
{
var fileList = new List<FileViewModel>();
//.. code to connect to the azure account and container
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
//In case blob container's ACL is private, the blob can't be accessed via simple URL. For that we need to
//create a Shared Access Signature (SAS) token which gives time/permission bound access to private resources.
var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),//Asssuming user stays on the page for an hour.
});
var blobUrl = blob.Uri.AbsoluteUri + sasToken;//This will ensure that user will be able to access the blob for one hour.
fileList.Add(new FileViewModel
{
FileName = blob.Name,
AzureUrl = blobUrl
});
}
}
return View(fileList)
}
cshtml视图
@model IEnumerable<FileViewModel>
<h2>File List</h2>
@foreach(var file in Model)
{
//link will be opened in a new tab
<a target="_blank" href="@file.AzureUrl">@file.FileName</a>
}
这仅适用于Blob的容器在此link中是公开的,解释如何创建和使用私有blob容器。感谢 GauravMantri 指出了这一点。