Azure Storage用法:使用Blob Storage

Posted 一指流砂

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
        }
    }
}

 

以上是关于Azure Storage用法:使用Blob Storage的主要内容,如果未能解决你的问题,请参考以下文章

Azure Queue Storage 基本用法 -- Azure Storage 之 Queue

使用 azure-storage-blob 或 azure-storage 上传和删除 Azure 存储 Blob

Azure.Cosmos 还是 Microsoft.Azure.Cosmos、Azure.Storage.Blob 还是 Microsoft.Azure.Storage.Blob?适用于 .NET C

如何用 Microsoft.Azure.Storage.Blob 替换 Microsoft.WindowsAzure.Storage

使用 @azure/storage-blob 将 blob 从一个存储帐户复制到另一个

使用PowerShell创建Azure Storage的SAS Token访问Azure Blob文件