zoukankan      html  css  js  c++  java
  • Azure Storage用法:使用Blob Storage

    Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob、Queue、File 和 Table。

    笔者在C# 消息队列-Microsoft Azure service bus 服务总线中介绍了 Queue Storage 的基本用法,本文将介绍 Blob Storage 的主要使用方法。

    Blob Storage可以看做是云端的文件系统。与桌面操作系统上不同,我们是通过REST API来进行对文件的操作。有关REST API的详细信息,请参见Blob 服务 API

    本文以邮件中的附件示例:

    using DBI.SaaS.MessageService.FileStore;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DBI.SaaS.MessageService.Controller
    {
        public class FileUploadController
        {
    
    
            public string Upload(Stream fileData, string extension)
            {
                //保存图片
                var store = new AzureStore()
                {
                    FileData = fileData,
                    StoreType = typeof(AzureFileStoreProvider),
                    ExtensionName = extension
                };
                //var data = (fileData as MemoryStream).ToArray();
                //var shortCut = data.MakeThumbnail(214, 166, "M");
                var storeProvider = StoreFactory.Create(store);
                storeProvider.SaveFile();
                return store.OutFileName;
            }
    
            public string Upload(Stream fileData, string extension, byte[] arr)
            {
                //保存图片
                var store = new AzureStore()
                {
                    FileData = fileData,
                    FileDataByteArray = arr,
                    StoreType = typeof(AzureFileStoreProvider),
                    ExtensionName = extension
                };
                //var data = (fileData as MemoryStream).ToArray();
                //var shortCut = data.MakeThumbnail(214, 166, "M");
                var storeProvider = StoreFactory.Create(store);
                storeProvider.SaveFile();
                return store.OutFileName;
            }
    
    
    
            /// <summary>
            /// 下载文件
            /// </summary>
            /// <param name="filepath"></param>
            /// <returns></returns>
            public Stream Download(string filepath, string type)
            {
                var store = new AzureStore()
                {
                    FileData = new MemoryStream(),
                    StoreType = typeof(AzureFileStoreProvider),
                    OutFileName = filepath
                };
                var storeProvider = StoreFactory.Create(store);
                storeProvider.GetFile(type);
                return store.FileData;
            }
        }
    }
    using Microsoft.Azure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Auth;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DBI.SaaS.MessageService.FileStore
    {
        public class AzureFileStoreProvider : IFileStoreProvider
        {
            static StorageCredentials credentials = new StorageCredentials(ConfigurationManager.AppSettings["StorageAccount"], ConfigurationManager.AppSettings["StorageKey"]);
            static CloudStorageAccount storageAccount = new CloudStorageAccount(credentials,
                new Uri(ConfigurationManager.AppSettings["BlobUri"]),
               null,
               null, null);
    
            /// <summary>
            /// 文件存储信息
            /// </summary>
            public IStore Store
            {
                get; set;
            }
    
            /// <summary>
            /// 获取文件
            /// </summary>
            public void GetFile(string type)
            {
                string fileinfo = Store.OutFileName;
                string[] pars = fileinfo.Split('-');
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                if (type == "s")
                {
                    CloudBlobContainer container = blobClient.GetContainerReference(pars[0] + "sc");
                    var blockBlob = container.GetBlobReference(pars[1]);
                    blockBlob.DownloadToStream(Store.FileData);
                }
                else
                {
                    CloudBlobContainer container = blobClient.GetContainerReference(pars[0]);
                    var blockBlob = container.GetBlobReference(pars[1]);
                    blockBlob.DownloadToStream(Store.FileData);
                }
            }
    
            /// <summary>
            /// 保存文件
            /// </summary>
            public void SaveFile()
            {
    
                // Retrieve storage account from connection string.
                //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                //    CloudConfigurationManager.GetSetting("StorageConnectionString"));
                // Create the blob client.
                try
                {
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    var containerName = "files" + DateTime.Now.ToString("yyyyMM");
                    var filename = Guid.NewGuid().ToString("N") + this.Store.ExtensionName;
                    // Retrieve reference to a previously created container.
                    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
                    container.CreateIfNotExists();
    
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
                    //blockBlob.UploadFromStream(this.Store.FileData);
                    blockBlob.UploadFromByteArray(this.Store.FileDataByteArray, 0, this.Store.FileDataByteArray.Length);
                    this.Store.OutFileName = containerName + "-" + filename;
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    this.Store.FileData.Close();
                    this.Store.FileData.Dispose();
                }
    
            }
    
            public void SaveFile(string containername, string filename)
            {
                try
                {
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    // Retrieve reference to a previously created container.
                    CloudBlobContainer container = blobClient.GetContainerReference(containername);
                    container.CreateIfNotExists();
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
                    blockBlob.UploadFromByteArray(this.Store.BytData, 0, this.Store.BytData.Length);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
    
            public void SaveFileNoImg()
            {
                // Retrieve storage account from connection string.
                //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                //    CloudConfigurationManager.GetSetting("StorageConnectionString"));
                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                var containerName = "files" + DateTime.Now.ToString("yyyyMM");
                // Retrieve reference to a previously created container.
                CloudBlobContainer container = blobClient.GetContainerReference(containerName);
                container.CreateIfNotExists();
                var filename = Guid.NewGuid().ToString("N") + this.Store.ExtensionName;
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
    
                // Retrieve reference to a blob named "myblob".
    
    
                // Create or overwrite the "myblob" blob with contents from a local file.
    
                blockBlob.UploadFromStream(this.Store.FileData);
                this.Store.FileData.Dispose();
                this.Store.OutFileName = containerName + "-" + filename;
            }
        }
    }
  • 相关阅读:
    常用的npm指令总结
    Mongoose基础
    2016总结与展望
    sleep与wait的区别
    查询平均分大于80分的学生
    求最大不重复子串
    快速排序
    按位与(&)运算的作用
    异或运算的作用
    java 字符串中的每个单词的倒序输出
  • 原文地址:https://www.cnblogs.com/xuwendong/p/6656481.html
Copyright © 2011-2022 走看看