iT邦幫忙

DAY 25
6

使用Asp.Net MVC打造Web Api系列 第 25

使用Asp.Net MVC打造Web Api (25) - 使用Azure Storage儲存圖片

在以往的網頁開發中,實際檔案的儲存一直是很麻煩的課題,有可能會受到硬碟空間大小的限制,或是不同台機器要共用Filer,還有如何確保檔案不會遺失等等,有許許多多的眉眉角角,也是無形的一種管理成本開銷,而Azure提供了專門的Storage服務,甚至還提供地理備援機制,讓我們檔案服務的可靠度大大提升,今天就要來像大家介紹如何在API中實現簡單的圖片上傳機制。
※開啟Azure Storage服務
首先我們先來建立一個儲存體用來存放圖片

  1. 進入Azure入口網站,點擊儲存體,選擇新增
  2. 輸入儲存體名稱並新增
  3. 新增成功

※新增商品圖片修改功能
在提供上傳圖片的服務之前,我們先在商品新增一個欄位來儲存圖片網址,並且提供一個方法讓使用者可以修改它的商品圖片。

  1. 修改Product Class,新增圖片欄位

        public class Product : EntityBase
        {            
            [StringLength(300)]
            public string ImagePath { get; set; }            
        }    
    
  2. 在套建管理員新增Migration和更新資料庫

        Add-Migration AddProductImagePath
    
        Update-Database
    
  3. 在DA建立修改商品圖片的程式碼

        public interface IProductRepository
        {
            IEnumerable<ProductForCategoryModel> GetProductByCategoryId(int categoryId);
    
            void InsertProduct(ProductModel productModel);
    
            void UpdateProductImagePath(int id, string imagePath);
        }
    
        public class ProductRepository : IProductRepository
        {
            public ShopContext ShopContext { get; set; }
    
            public ProductRepository(ShopContext context)
            {
                this.ShopContext = context;
            }
    
            public void UpdateProductImagePath(int id, string imagePath)
            {
                var product = this.ShopContext.Products
                                              .Where(i => i.Id == id)
                                              .FirstOrDefault();
    
                if (product != null)
                {
                    product.ImagePath = imagePath;
                }
    
                this.ShopContext.SaveChanges();
            }
        }        
    

※新增Azure檔案上傳服務

  1. 新增IFileRepository介面,開放兩個參數作為分類依據

網址格式: http://hostname/{Container}/{Id}/{FileName}

        public interface IFileRepository
        {
            string UploadFile(string containerName, string groupName, HttpPostedFileBase file);
        }
  1. 使用Nuget加入Azure.Storage Library

  2. 到Azure儲存體點選管理儲存金鑰

  3. 記下主要金鑰內容

  4. 在網站的AppSetting新增Storage的連線字串,包含主要金鑰

        <add key="azure.blob.connectionstring" value="DefaultEndpointsProtocol=https;AccountName=apiimage;AccountKey=xxxx;BlobEndpoint=http://apiimage.blob.core.windows.net/" />
    
  5. 撰寫上傳檔案至Azure Storage的程式碼

        public class FileRepository : IFileRepository
        {
            public string UploadFile(string containerName, string groupName, HttpPostedFileBase file)
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("azure.blob.connectionstring"));
    
                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                // Retrieve a reference to a container. 
                CloudBlobContainer container = blobClient.GetContainerReference(containerName.ToLower());
    
                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
    
                container.SetPermissions(
                         new BlobContainerPermissions
                         {
                             PublicAccess =
                                 BlobContainerPublicAccessType.Blob
                         });
    
                var fileName = groupName + "/" + file.FileName;
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
    
                blockBlob.Properties.ContentType = file.ContentType;
                blockBlob.UploadFromStream(file.InputStream);
    
                return blockBlob.Uri.AbsoluteUri;
            }
        }
    

延伸閱讀:
* How to use the Windows Azure Blob Storage Service in .NET

※測試圖片上傳
接下來我們模擬上傳圖片,測試是否有上傳到Azure Storage和更新商品圖片

  1. 使用Fiddle執行Post檔案
  2. 收到成功訊息
  3. 進入Storage的容器Product中,有圖片存在
  4. 商品資料也有確實更新

※本日小結
透過Azure Storage服務,可以非常快速的就實現檔案上傳,也可以讓我們省去許多管理儲存空間的麻煩,例如像File Server的維護,還能提供高可用性的儲存空間,甚至是異地備援等等,而在使用上也擁有非常多的彈性,更不需要擔心硬碟空間不足的問題,大家可以依照自己的需求評估使用,關於今天的內容歡迎大家一起討論 ^_^


上一篇
使用Asp.Net MVC打造Web Api (24) - 使用Azure Cache將資料進行Cache
下一篇
使用Asp.Net MVC打造Web Api (26) - 使用Azure Service Bus處理瞬間大量請求
系列文
使用Asp.Net MVC打造Web Api30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言