如何在 Azure Storage Blobs 內增加子資料夾?

 

Windows Azure Storage BLOB 概述 中所提到的,Windows Azure Storage Blobs 沒有子資料夾的概念,所謂子資料夾就是檔案名稱的一部分。例如

 

https://myaccount.blob.core.windows.net/pictures/trips/seattle/spaceneedle.jpg

乍看之下您或許會以為有多個樹狀層級的資料夾 "pictures"、"trips" 與 "seattle" 會對應到此 blob 的命名空間,但實際上所有路徑中許多成員僅是二進制檔案自己的名稱而已。在這個例子中,容器的名稱 (container) 為"pictures",所儲存的二進制檔案名稱則是 "trips/seattle/spaceneedle.jpg"。

 

附上一個 Console Mode Application 範例程式碼,把一個本機硬碟內的圖片 IMG_2956.JPG 上傳到 Windows Azure Storage 一個名為 Image 的容器 (Container) ,而這個 BLOB 檔案名稱為 subfolder1\subfolder1a\IMG_2956.JPG

usingSystem ;

usingSystem.Collections.Generic ;

usingSystem.Linq ;

usingSystem.Text ;

// Add some namespace

usingSystem.Configuration ;

usingMicrosoft.WindowsAzure.Storage ;

usingMicrosoft.WindowsAzure.Storage.Auth ;

usingMicrosoft.WindowsAzure.Storage.Blob ;

namespaceBLOBSample

{

class Program

    {

staticvoidMain ( string [] args )

        {

// Retrieve storage account from connection string.

            CloudStorageAccount storageAccount= CloudStorageAccount.Parse ( "DefaultEndpointsProtocol=https;AccountName=[Your account name];AccountKey=[Your Key]" );

// Create the blob client.

            CloudBlobClient blobClient=storageAccount.CreateCloudBlobClient ();

// Retrieve reference to a previously created container.

            CloudBlobContainer container=blobClient.GetContainerReference ( "image" );

// Retrieve reference to a blob named " subfolder1\\subfolder1a\\IMG_2956.JPG ".

            CloudBlockBlob blockBlob=container.GetBlockBlobReference ( "subfolder1\\subfolder1a\\IMG_2956.JPG" );

// Create or overwrite the " subfolder1\\subfolder1a\\IMG_2956.JPG " blob with contents from a local file IMG_2956.JPG.

using ( varfileStream=System.IO.File.OpenRead (@"IMG_2956.JPG"))

            {

blockBlob.UploadFromStream ( fileStream );

            }

System.Console.WriteLine ( "Complete!" );

System.Console.ReadKey ();

        }

    }

}

若是用 CloudXplorer 這類工具,為了將 Azure Storage Blobs 模擬的像檔案總管,讓使用者看起像是有兩層子資料夾 subfolder1 與 subfolder1a,但是請記得實際上這是 image 的容器 (Container) 內儲存了一個檔案名稱為 subfolder1\subfolder1a\IMG_2956.JPG 的二進制檔案。

clip_image002