• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ASP.NETCore2.0中的AzureBlob存储

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

问题

如何在ASP.NET Core中使用Azure Blob存储

创建一个类库并添加NuGet包 - WindowsAzure.Storage

添加一个类来封装设置,

  1. publicclass AzureBlobSetings

  2. {

  3. public AzureBlobSetings(string storageAccount,

  4. string storageKey,

  5. string containerName)

  6. {

  7. if (string.IsNullOrEmpty(storageAccount))

  8. thrownew ArgumentNullException("StorageAccount");

  9. if (string.IsNullOrEmpty(storageKey))

  10. thrownew ArgumentNullException("StorageKey");

  11. if (string.IsNullOrEmpty(containerName))

  12. thrownew ArgumentNullException("ContainerName");

  13. this.StorageAccount = storageAccount;

  14. this.StorageKey = storageKey;

  15. this.ContainerName = containerName;

  16. }

  17. public string StorageAccount { get; }

  18. public string StorageKey { get; }

  19. public string ContainerName { get; }

  20. }

添加一个类来封装一个blob项目,

  1. publicclass AzureBlobItem

  2. {

  3. public AzureBlobItem(IListBlobItem item)

  4. {

  5. this.Item = item;

  6. }

  7. public IListBlobItem Item { get; }

  8. public bool IsBlockBlob => Item.GetType() == typeof(CloudBlockBlob);

  9. public bool IsPageBlob => Item.GetType() == typeof(CloudPageBlob);

  10. public bool IsDirectory => Item.GetType() == typeof(CloudBlobDirectory);

  11. public string BlobName => IsBlockBlob ? ((CloudBlockBlob)Item).Name :

  12. IsPageBlob ? ((CloudPageBlob)Item).Name :

  13. IsDirectory ? ((CloudBlobDirectory)Item).Prefix :

  14. "";

  15. public string Folder => BlobName.Contains("/") ?

  16. BlobName.Substring(0, BlobName.LastIndexOf("/")) : "";

  17. public string Name => BlobName.Contains("/") ?

  18. BlobName.Substring(BlobName.LastIndexOf("/") + 1) : BlobName;

  19. }

Add a class to encapsulate storage access. Add a private helper methods to access storage,

  1. private async Task<CloudBlobContainer> GetContainerAsync()

  2. {

  3. //Account

  4. CloudStorageAccount storageAccount = new CloudStorageAccount(

  5. new StorageCredentials(settings.StorageAccount, settings.StorageKey), false);

  6. //Client

  7. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

  8. //Container

  9. CloudBlobContainer blobContainer =

  10. blobClient.GetContainerReference(settings.ContainerName);

  11. await blobContainer.CreateIfNotExistsAsync();

  12. return blobContainer;

  13. }

  14. private async Task<CloudBlockBlob> GetBlockBlobAsync(string blobName)

  15. {

  16. //Container

  17. CloudBlobContainer blobContainer = await GetContainerAsync();

  18. //Blob

  19. CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(blobName);

  20. return blockBlob;

  21. }

  22. private async Task<List<AzureBlobItem>> GetBlobListAsync(

  23. bool useFlatListing = true)

  24. {

  25. //Container

  26. CloudBlobContainer blobContainer = await GetContainerAsync();

  27. //List

  28. var list = new List<AzureBlobItem>();

  29. BlobContinuationToken token = null;

  30. do

  31. {

  32. BlobResultSegment resultSegment =

  33. await blobContainer.ListBlobsSegmentedAsync("", useFlatListing,

  34. new BlobListingDetails(), null, token, null, null);

  35. token = resultSegment.ContinuationToken;

  36. foreach (IListBlobItem item in resultSegment.Results)

  37. {

  38. list.Add(new AzureBlobItem(item));

  39. }

  40. } while (token != null);

  41. return list.OrderBy(i => i.Folder).ThenBy(i => i.Name).ToList();

  42. }

现在添加公共方法来上传和下载blob项目,

  1. public async Task UploadAsync(string blobName, string filePath)

  2. {

  3. //Blob

  4. CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);

  5. //Upload

  6. using (var fileStream = System.IO.File.Open(filePath, FileMode.Open))

  7. {

  8. fileStream.Position = 0;

  9. await blockBlob.UploadFromStreamAsync(fileStream);

  10. }

  11. }

  12. public async Task UploadAsync(string blobName, Stream stream)

  13. {

  14. //Blob

  15. CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);

  16. //Upload

  17. stream.Position = 0;

  18. await blockBlob.UploadFromStreamAsync(stream);

  19. }

  20. public async Task<MemoryStream> DownloadAsync(string blobName)

  21. {

  22. //Blob

  23. CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);

  24. //Download

  25. using (var stream = new MemoryStream())

  26. {

  27. await blockBlob.DownloadToStreamAsync(stream);

  28. return stream;

  29. }

  30. }

  31. public async Task DownloadAsync(string blobName, string path)

  32. {

  33. //Blob

  34. CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);

  35. //Download

  36. await blockBlob.DownloadToFileAsync(path, FileMode.Create);

  37. }

添加方法来获取blob项目列表,

  1. public async Task<List<AzureBlobItem>> ListAsync()

  2. {

  3. return await GetBlobListAsync();

  4. }

  5. public async Task<List<string>> ListFoldersAsync()

  6. {

  7. var list = await GetBlobListAsync();

  8. return list.Where(i => !string.IsNullOrEmpty(i.Folder))

  9. .Select(i => i.Folder)

  10. .Distinct()

  11. .OrderBy(i => i)

  12. .ToList();

  13. }

注入和使用存储助手,

  1. publicclass HomeController : Controller

  2. {

  3. private readonly IAzureBlobStorage blobStorage;

  4. public HomeController(IAzureBlobStorage blobStorage)

  5. {

  6. this.blobStorage = blobStorage;

  7. }

注意

示例代码具有一个控制器,其中包含列出,下载和上载项目的操作。

在 ASP.NET核心 Web应用程序中,配置服务,

  1. publicvoid ConfigureServices(

  2. IServiceCollection services)

  3. {

  4. services.AddScoped<IAzureBlobStorage>(factory =>

  5. {

  6. returnnew AzureBlobStorage(new AzureBlobSetings(

  7. storageAccount: Configuration["Blob_StorageAccount"],

  8. storageKey: Configuration["Blob_StorageKey"],

  9. containerName: Configuration["Blob_ContainerName"]));

  10. });

  11. services.AddMvc();

  12. }

讨论

示例代码将要求您设置Azure帐户,Blob存储帐户和容器。这些指令可以在这里找到


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap