【问题标题】:Trying to link to azure blob files on a cshtml page尝试链接到 cshtml 页面上的 azure blob 文件
【发布时间】:2014-09-08 12:48:00
【问题描述】:

我已将一些 jpg 和 txt 文件上传到 azure blob 存储,并且我已阅读 this tutorial,所以我知道如何检索它们。

我想弄清楚的是当我的 cshtml 页面中的链接被点击时如何加载和链接到文件。

谢谢!

【问题讨论】:

  • 当用户点击您的 .cshtml 中的链接时,您要下载文件吗?
  • @Overmachine 没问题,尽管在新选项卡中打开文件会更好。
  • @viperguynaz 我真的不知道如何以一种可以在网页中访问的方式存储文件,所以我不知道该尝试什么。

标签: c# asp.net-mvc-4 azure razor azure-blob-storage


【解决方案1】:

如果你知道如何检索你知道如何加载它们的文件,你可以像这样设置一些非常简单的东西。

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

【讨论】:

  • 如果 blob 容器的 ACL 是私有的会怎样?最好提供具有读取权限的 SAS URL 而不是 blob URI。
  • @GauravMantri 是的,这仅在容器是公共的情况下才有效,基于提供的链接azure.microsoft.com/en-us/documentation/articles/…
  • @GauravMantri 一点也不,去吧
猜你喜欢
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 2020-12-17
  • 2016-12-12
  • 1970-01-01
  • 2021-06-07
  • 2019-09-05
  • 1970-01-01
相关资源
最近更新 更多