一个使用微软Azure blob实现文件下载功能的实例-附带源文件

Running the sample

Please follow the steps below.

Step 1: Open the CSAzureServeFilesFromBlobStorage.sln as Administrator. Expand the CSAzureServeFilesFromBlobStorage application and set CSAzureServeFilesFromBlobStorage azure application as the startup project, press F5 to display Default.aspx page.

Step 2: Please add your Windows Azure Storage Account and Key in the Windows Azure settings, "StorageConnections". If you do not have one, please use Windows Azure Storage Emulator.  You will see a web page with two unavailable links on it. Please click the link "Add default resources page" to redirect to default resources adding page.

Step 3:  Click the "Click to upload the default resources" button to upload your resources to Windows Azure Blob Storage and Table Storage. You can find "Microsoft.jpg, MSDN.jpg and Site.css" in the "Files" folder. These files will be uploaded to the blob container and their information will be stored in table storage.

Step 4: The files have been uploaded now. You can go to Microsoft Windows Azure Management Portal or use Azure Storage Explore tool to view your resources. The default blob container name is "container" and default table name is "files".

Step 5: Go back to the Default.aspx page. You will find the uploaded resources appear on it. Click the link to view them.

Step 6: In this sample, you can access jpg and css files (also including .aspx files). Files of other types, such as .htm files, cannot be reached.

Step 7: Validation finished.

Using the Code

Step 1. Create a C# "Windows Azure Project" in Visual Studio 2012. Name it as "CSAzureServeFilesFromBlobStorage". Add a Web Role and name it as "ServeFilesFromBlobStorageWebRole"; add a class library and name it as "TableStorageManager". Make sure the class library‘s target framework is .NET Framework 4.5 (Not .NET Framework 4.5 Client Profile).

Step 2. Add 3 class files in TableStorageManager class library, which is used to package the bottom table storage methods. Try to add Windows Azure references and Data Service client reference.

Microsoft.WindowsAzure.Diagonostics

Microsoft.WindowsAzure.ServiceRuntime

Microsoft.WindowsAzure.StorageClient

System.Data.Service.Client

The FileEntity class is a table storage entity class; it includes some basic properties. The FileContext class is used to create queries for table services. You can also add paging method for table storage. The FileDataSource package the bottom layer methods (about cloud account, TableServiceContext, credentials, etc)

C#

Edit|Remove

csharp

public class FileDataSource

{

private static CloudStorageAccount account;

private FileContext context;

public FileDataSource()

{

// Create table storage client via cloud account.

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

CloudTableClient client = account.CreateCloudTableClient();

client.CreateTableIfNotExist("files");

// Table context properties.

context = new FileContext(account.TableEndpoint.AbsoluteUri, account.Credentials);

context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));

context.IgnoreResourceNotFoundException = true;

context.IgnoreMissingProperties = true;

}

/// <summary>

/// Get all entities method.

/// </summary>

/// <returns></returns>

public IEnumerable<FileEntity> GetAllEntities()

{

var list = from m in this.context.GetEntities

select m;

return list;

}

/// <summary>

/// Get table rows by partitionKey.

/// </summary>

/// <param name="partitionKey"></param>

/// <returns></returns>

public IEnumerable<FileEntity> GetEntities(string partitionKey)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey

select m;

return list;

}

/// <summary>

/// Get specify entity.

/// </summary>

/// <param name="partitionKey"></param>

/// <param name="fileName"></param>

/// <returns></returns>

public FileEntity GetEntitiesByName(string partitionKey, string fileName)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey && m.FileName == fileName

select m;

if (list.Count() > 0)

return list.First<FileEntity>();

else

return null;

}

/// <summary>

/// Add an entity.

/// </summary>

/// <param name="entity"></param>

public void AddFile(FileEntity entity)

{

this.context.AddObject("files", entity);

this.context.SaveChanges();

}

/// <summary>

/// Make a judgment to check if file is exists.

/// </summary>

/// <param name="filename"></param>

/// <param name="partitionKey"></param>

/// <returns></returns>

public bool FileExists(string filename, string partitionKey)

{

IEnumerable<FileEntity> list = from m in this.context.GetEntities

where m.FileName == filename && m.PartitionKey == partitionKey

select m;

if (list.Count()>0)

{

return true;

}

else

{

return false;

}

}

}

public class FileDataSource

{

private static CloudStorageAccount account;

private FileContext context;

public FileDataSource()

{

// Create table storage client via cloud account.

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

CloudTableClient client = account.CreateCloudTableClient();

client.CreateTableIfNotExist("files");

// Table context properties.

context = new FileContext(account.TableEndpoint.AbsoluteUri, account.Credentials);

context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));

context.IgnoreResourceNotFoundException = true;

context.IgnoreMissingProperties = true;

}

/// <summary>

/// Get all entities method.

/// </summary>

/// <returns></returns>

public IEnumerable<FileEntity> GetAllEntities()

{

var list = from m in this.context.GetEntities

select m;

return list;

}

/// <summary>

/// Get table rows by partitionKey.

/// </summary>

/// <param name="partitionKey"></param>

/// <returns></returns>

public IEnumerable<FileEntity> GetEntities(string partitionKey)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey

select m;

return list;

}

/// <summary>

/// Get specify entity.

/// </summary>

/// <param name="partitionKey"></param>

/// <param name="fileName"></param>

/// <returns></returns>

public FileEntity GetEntitiesByName(string partitionKey, string fileName)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey && m.FileName == fileName

select m;

if (list.Count() > 0)

return list.First<FileEntity>();

else

return null;

}

/// <summary>

/// Add an entity.

/// </summary>

/// <param name="entity"></param>

public void AddFile(FileEntity entity)

{

this.context.AddObject("files", entity);

this.context.SaveChanges();

}

/// <summary>

/// Make a judgment to check if file is exists.

/// </summary>

/// <param name="filename"></param>

/// <param name="partitionKey"></param>

/// <returns></returns>

public bool FileExists(string filename, string partitionKey)

{

IEnumerable<FileEntity> list = from m in this.context.GetEntities

where m.FileName == filename && m.PartitionKey == partitionKey

select m;

if (list.Count()>0)

{

return true;

}

else

{

return false;

}

}

}

Step 3. Then we need add a class in ServeFilesFromBlobStorageWebRole project as an HttpModuler to check the types of requested files and access the files in Blob Storage.

C#

Edit|Remove

csharp

public void Init(HttpApplication context)

{

context.BeginRequest += new EventHandler(this.Application_BeginRequest);

}

/// <summary>

/// Check file types and request it by cloud blob API.

/// </summary>

/// <param name="source"></param>

/// <param name="e"></param>

private void Application_BeginRequest(Object source,EventArgs e)

{

string url = HttpContext.Current.Request.Url.ToString();

string fileName = url.Substring(url.LastIndexOf(‘/‘) + 1).ToString();

string extensionName = string.Empty;

if (fileName.Substring(fileName.LastIndexOf(‘.‘) + 1).ToString().Equals("aspx"))

{

return;

}

if (!fileName.Equals(string.Empty))

{

extensionName = fileName.Substring(fileName.LastIndexOf(‘.‘) + 1).ToString();

if (!extensionName.Equals(string.Empty))

{

string contentType = this.GetContentType(fileName);

if (contentType.Equals(string.Empty))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

};

{

FileDataSource dataSource = new FileDataSource();

string paritionKey = this.GetPartitionName(extensionName);

if (String.IsNullOrEmpty(paritionKey))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

}

FileEntity entity = dataSource.GetEntitiesByName(paritionKey, "Files/" + fileName);

if (entity != null)

HttpContext.Current.Response.Redirect(entity.FileUrl);

else

HttpContext.Current.Server.Transfer("NoResources.aspx");

}

}

}

}

/// <summary>

/// Get file‘s Content-Type.

/// </summary>

/// <param name="filename"></param>

/// <returns></returns>

public string GetContentType(string filename)

{

string res = string.Empty;

switch (filename.Substring(filename.LastIndexOf(‘.‘) + 1).ToString().ToLower())

{

case "jpg":

res = "image/jpg";

break;

case "css":

res = "text/css";

break;

}

return res;

}

/// <summary>

/// Get file‘s partitionKey.

/// </summary>

/// <param name="extensionName"></param>

/// <returns></returns>

public string GetPartitionName(string extensionName)

{

string partitionName = string.Empty;

switch(extensionName)

{

case "jpg":

partitionName = "image";

break;

case "css":

partitionName = "css";

break;

}

return partitionName;

}

public void Init(HttpApplication context)

{

context.BeginRequest += new EventHandler(this.Application_BeginRequest);

}

/// <summary>

/// Check file types and request it by cloud blob API.

/// </summary>

/// <param name="source"></param>

/// <param name="e"></param>

private void Application_BeginRequest(Object source,EventArgs e)

{

string url = HttpContext.Current.Request.Url.ToString();

string fileName = url.Substring(url.LastIndexOf(‘/‘) + 1).ToString();

string extensionName = string.Empty;

if (fileName.Substring(fileName.LastIndexOf(‘.‘) + 1).ToString().Equals("aspx"))

{

return;

}

if (!fileName.Equals(string.Empty))

{

extensionName = fileName.Substring(fileName.LastIndexOf(‘.‘) + 1).ToString();

if (!extensionName.Equals(string.Empty))

{

string contentType = this.GetContentType(fileName);

if (contentType.Equals(string.Empty))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

};

{

FileDataSource dataSource = new FileDataSource();

string paritionKey = this.GetPartitionName(extensionName);

if (String.IsNullOrEmpty(paritionKey))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

}

FileEntity entity = dataSource.GetEntitiesByName(paritionKey, "Files/" + fileName);

if (entity != null)

HttpContext.Current.Response.Redirect(entity.FileUrl);

else

HttpContext.Current.Server.Transfer("NoResources.aspx");

}

}

}

}

/// <summary>

/// Get file‘s Content-Type.

/// </summary>

/// <param name="filename"></param>

/// <returns></returns>

public string GetContentType(string filename)

{

string res = string.Empty;

switch (filename.Substring(filename.LastIndexOf(‘.‘) + 1).ToString().ToLower())

{

case "jpg":

res = "image/jpg";

break;

case "css":

res = "text/css";

break;

}

return res;

}

/// <summary>

/// Get file‘s partitionKey.

/// </summary>

/// <param name="extensionName"></param>

/// <returns></returns>

public string GetPartitionName(string extensionName)

{

string partitionName = string.Empty;

switch(extensionName)

{

case "jpg":

partitionName = "image";

break;

case "css":

partitionName = "css";

break;

}

return partitionName;

}

Step 4. Add a Default web page to show links of some examples, and add a FileUploadPage to upload some default resources to Storage for testing.

C#

Edit|Remove

csharp

public partial class FileUploadPage : System.Web.UI.Page

{

private static CloudStorageAccount account;

public List<FileEntity> files = new List<FileEntity>();

protected void Page_Load(object sender, EventArgs e)

{

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

}

/// <summary>

/// Upload existing resources. ("Files" folder)

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void btnUpload_Click(object sender, EventArgs e)

{

FileDataSource source = new FileDataSource();

List<string> nameList = new List<string>() { "Files/Microsoft.jpg", "Files/MSDN.jpg", "Files/Site.css" };

CloudBlobClient client = account.CreateCloudBlobClient();

CloudBlobContainer container = client.GetContainerReference("container");

container.CreateIfNotExist();

var permission = container.GetPermissions();

permission.PublicAccess = BlobContainerPublicAccessType.Container;

container.SetPermissions(permission);

bool flag = false;

foreach (string name in nameList)

{

if (name.Substring(name.LastIndexOf(‘.‘) + 1).Equals("jpg") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "image"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("image");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The image file {0} is uploaded successes.
", name);

}

}

else if (name.Substring(name.LastIndexOf(‘.‘) + 1).Equals("css") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "css"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("css");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The css file {0} is uploaded successes.
", name);

}

}

}

if (!flag)

{

lbContent.Text = "You had uploaded these resources";

}

}

protected void LinkButton1_Click(object sender, EventArgs e)

{

Response.Redirect("Default.aspx");

}

}

public partial class FileUploadPage : System.Web.UI.Page

{

private static CloudStorageAccount account;

public List<FileEntity> files = new List<FileEntity>();

protected void Page_Load(object sender, EventArgs e)

{

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

}

/// <summary>

/// Upload existing resources. ("Files" folder)

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void btnUpload_Click(object sender, EventArgs e)

{

FileDataSource source = new FileDataSource();

List<string> nameList = new List<string>() { "Files/Microsoft.jpg", "Files/MSDN.jpg", "Files/Site.css" };

CloudBlobClient client = account.CreateCloudBlobClient();

CloudBlobContainer container = client.GetContainerReference("container");

container.CreateIfNotExist();

var permission = container.GetPermissions();

permission.PublicAccess = BlobContainerPublicAccessType.Container;

container.SetPermissions(permission);

bool flag = false;

foreach (string name in nameList)

{

if (name.Substring(name.LastIndexOf(‘.‘) + 1).Equals("jpg") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "image"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("image");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The image file {0} is uploaded successes.
", name);

}

}

else if (name.Substring(name.LastIndexOf(‘.‘) + 1).Equals("css") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "css"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("css");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The css file {0} is uploaded successes.
", name);

}

}

}

if (!flag)

{

lbContent.Text = "You had uploaded these resources";

}

}

protected void LinkButton1_Click(object sender, EventArgs e)

{

Response.Redirect("Default.aspx");

}

}

Step 5. Please add your Windows Azure Storage account name and key in the Azure project. If you do not have one, use Windows Azure Storage Emulator for testing.

Step 6. Build the application and you can debug it.

源码下载

时间: 2024-08-11 18:36:02

一个使用微软Azure blob实现文件下载功能的实例-附带源文件的相关文章

presto访问 Azure blob storage

当集群使用Azure Blog Storage时,prestoDB无法获取返回结果,在此记录下 如下,hive里面的两个表,一个使用的是本地的hdfs,一个是使用 azure blob storage, presto 能访问到hive里面的所有表结构,能查询本地hdfs的hive表,如下: 在返回查询数据时,本地hdfs 存储正常 存储在azure blob storage上的数据返回异常,如下: 问题待解决中....... 收集资料: http://stackoverflow.com/ques

前端:文件下载功能

需求:页面上有一个下载按钮,点击后实行文件下载功能. var exportURL = "/moduleName/rest/exportdata?startDate=" + startDate + "&endDate=" + endDate; console.log(exportURL); ajaxWrapper(exportURL, function () { window.open(exportURL, "_blank");//打开一个

阿里云ONS而微软Azure Service Bus体系结构和功能比较

阿里云ONS而微软Azure Service bus体系结构和功能比较 版权所有所有,转载请注明出处http://blog.csdn.net/yangzhenping.谢谢! 阿里云的开放消息服务: 一.如图所看到的,ProducerID1 的producer 实例有三个,可能是部署在三个机器上的三个进程,也可能是一台机 器上的三个进程. 每一个实例都会发送TopicA 的消息.同理,ProducerID2 与之类似. 二.ConsumerID1 有三个实例,假设是集群消费方式,那么每一个实例消

微软Azure云主机及blob存储的网络性能测试

  微软Azure云主机及blob存储的网络性能测试 1. 测试目的 本次测试的目的在于对微软Azure的云主机.blob存储的网络性能以及DNS解析的稳定性做相关测试,评估其是否能够满足我们业务的需求. 2. 测试项目 ? 微软Azure云主机的网络性能 ? 微软blob存储的网络性能 ? DNS解析稳定性测试 3. 测试方法 本次测试使用多种第三方分布式工具作为访问源及评测工具,比照测试结果数据,以综合评估微软Azure的网络性能及稳定性. 4. 网络性能测试 4.1. 网络带宽测试 我们通

一个基于Microsoft Azure、ASP.NET Core和Docker的博客系统

原文地址: http://www.cnblogs.com/daxnet/p/6139317.html 2008年11月,我在博客园开通了个人帐号,并在博客园发表了自己的第一篇博客.当然,我写博客也不是从2008年才开始的,在更早时候,也在CSDN和系统分析员协会(之后名为“希赛网”)个人空间发布过一些与编程和开发相关的文章.从入行到现在,我至始至终乐于与网友分享自己的所学所得,希望会有更多的同我一样的业内朋友能够在事业上取得成功,也算是为我们的软件事业贡献自己的一份力量吧,这也是我在博客园建博客

Python 操作 Azure Blob Storage

笔者在<Azure 基础:Blob Storage>一文中介绍了 Azure Blob Storage 的基本概念,并通过 C# 代码展示了如何进行基本的操作.最近笔者需要在 Linux 系统中做类似的事情,于是决定使用 Azure 提供的 Azure Storage SDK for Python 来操作 Blob Storage.这样今后无论在 Windows 上还是 Linux上,都用 Python 就可以了.对 Azure Blob Storage 概念还不太熟悉的同学请先参考前文. 安

Windows Azure HandBook (6) Azure带宽与Azure Blob云存储

<Windows Azure Platform 系列文章目录> 在笔者这几年Azure售前工作中,经常会遇到客户提同样的问题:Azure 虚拟机的带宽是多少?Azure提供独享带宽吗?这个项目我们需要200兆的独享带宽. 当遇到这种情况的时候,笔者就会问客户:请问您需要独享带宽的目的是什么呢? 客户经常会回答:这个应用需要视频(大文件)的上传下载功能,或者是并发用户数巨大,需要独享带宽来相应更多的Internet请求. 这种情况我表示非常理解,因为我们平时在购买电信宽带的时候,都是购买30M,

免费电子书:微软Azure基础之Azure Automation

(此文章同时发表在本人微信公众号"dotNET每日精华文章") Azure Automation是Azure内置的一项自动化运维基础功能,微软为了让大家更快上手使用这项功能,特意推出了一本免费电子书供大家下载阅读. 随着Azure在各国的不断落地和推广,微软也加大了Azure技术的布道工作.最近微软就开始发布一套名为"微软Azure基础(Microsoft Azure Essentials)"的系列电子书,第一本涉及Azure的基础知识,而第二本就详细讲述了Azur

怎样使用 OneAPM 监控微软 Azure Cloud Service ?

不知不觉微软 Azure 已经进入中国市场近两年的时间.那么 Azure 平台的性能到底怎样?资源载入的延迟.虚拟机的稳定性等问题是否切实满足客户期许.这些都是大家对微软 Azure 这个国外的云服务使者非常关注的问题. 市场对 IaaS 云服务商的对照评測报告数不胜数,非常难说谁家的评測报告准确可靠. 况且国内公网网络稳定情况与国外存在一定的差距.在这样一个相对不稳定的环境下.公有云服务的 SLA 对于客户的终于使用体验非常难全然保证.怎样可以帮助客户及时了解自己用户的真实体验.採用有效的工具