Slicedbread
Slicedbread

Reputation: 2244

Trying to link to azure blob files on a cshtml page

I've uploaded some jpg and txt files to an azure blob store and I've read this tutorial so I know how to retrieve them.

What I'm trying to figure out is how to load and link to the files when a link in my cshtml page is clicked.

Thanks!

Upvotes: 2

Views: 3037

Answers (1)

Overmachine
Overmachine

Reputation: 1733

If you know how to retrieve the files you know how to load them, you can set up something very simple like this.

the ViewModel which is going to represent the data that you want to display on your view/page.

public class FileViewModel 
{

  public string FileName {get; set;}
  public string AzureUrl {get; set;}

}

The controller action

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)
}

the cshtml view

@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>
}

This will only work if the Blob's container is public in this link explain how to create and use private blob containers. thanks to GauravMantri who pointed that out.

Upvotes: 7

Related Questions