Mit*_*tch 4 asp.net-mvc azure azure-storage-blobs razor
我正在使用ASP MVC 5 Razor和Microsoft Azure Blob存储.我可以使用MVC成功地将文档和图像上传到Blob存储,但我很难找到一些MVC示例如何下载和显示文件.
如果将blob存储为公共文件,那么执行此操作将非常简单,但我需要它们是私有的.
任何人都可以给我任何实例或指导如何实现这一目标?
我在下面有一些代码似乎可以检索Blob,但我不知道如何在MVC中使用它来实际在浏览器中显示它.
var fullFileName = "file1.pdf";
var containerName = "default";
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AttachmentStorageConnection"].ConnectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
// Retrieve reference to a blob ie "picture.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fullFileName);
Run Code Online (Sandbox Code Playgroud)
Ale*_*x S 13
我根据你的评论作出假设
如果将blob存储为公共文件,那么执行此操作将非常简单,但我需要它们是私有的
因为blob是私有的,所以你试图通过mvc控制器将一个字节数组返回给客户端.
但是,另一种方法是使用SharedAccessSignature为客户端提供对blob的临时访问,然后您可以将其作为公共URL访问.可以在控制器中指定URL有效的时间段.由于客户端将直接从存储中下载文件,因此这也具有从控制器带走负载的优势.
// view model
public class MyViewModel
{
string FileUrl {get; set;}
}
// controller
public ActionResult MyControllerAction
{
var readPolicy = new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(5)
};
// Your code ------
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings ["AttachmentStorageConnection"].ConnectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
// Retrieve reference to a blob ie "picture.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fullFileName);
//------
var newUri = new Uri(blockBlob.Uri.AbsoluteUri + blockBlob.GetSharedAccessSignature(readPolicy));
var viewModel = new MyViewModel()
{
FileUrl = newUri.ToString()
};
return View("MyViewName", viewModel);
}
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,您可以使用视图模型值
//image
<img src="@Model.FileUrl" />
//in a new tab
<a href="@Model.FileUrl" target="_blank">`Open in new window`</a>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4229 次 |
| 最近记录: |