Blob 服務提供二進位檔案和文字檔的儲存。通過Blob的 REST API 能夠訪問2種資源: Containers 和 Blobs。容器可以看做包含多個檔案的檔案夾,而blob便是屬於某個容器的檔案。有如下2種blob:
- Block Blobs: 該類型用於流式訪問。
- Page Blobs: 該類型用於隨機讀寫操作,能夠向blob中寫入一部分位元組。
Block Blobs 可以通過2種方法建立。 不超過64MB 的Block blobs 可以通過調用Put Blob 操作進行上傳。大於64 MB的 Block blobs 必須分塊上傳,每塊不超過4MB。當所有的分塊成功上傳之後,通過調用Put
Block List操作進行合并,成為單個連續的blob。Block blob目前最大支援200GB。
Page blobs 可以由調用Put Blob操作來建立和初始化,支援最大尺寸。通過調用Put Page 操作,向page blob寫入內容。Page blob 目前最大支援 1 TB。
Blobs 支援條件更新,更多請參見:
- "Understanding Block Blobs and Page Blobs" on MSDN.
- "Blob Service Concepts" on MSDN.
- "Blob Service API" on MSDN.
- "Windows Azure Storage Client Library" on MSDN.
以下代碼實現PutBlock檔案塊,最後需調用 PutBlockList實現最後寫入檔案。
主要代碼如下:(PutBlock返回的blockIds數組,最後要將此數組傳入PutBlockList)
// Put block - upload a block (portion) of a blob. // Return true on success, false if already exists, throw exception on error. public bool PutBlock(string containerName, string blobName, int blockId, string[] blockIds, byte[] content) { try { CloudBlobContainer container = BlobClient.GetContainerReference(containerName); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); string blockIdBase64 = Convert.ToBase64String(System.BitConverter.GetBytes(blockId)); UTF8Encoding utf8Encoding = new UTF8Encoding(); using (MemoryStream memoryStream = new MemoryStream(content)) { blob.PutBlock(blockIdBase64, memoryStream, null); } blockIds[blockId] = blockIdBase64; return true; } catch (StorageClientException ex) { if ((int)ex.StatusCode == 404) { return false; } throw; } } // Put block list - complete creation of blob based on uploaded content. // Return true on success, false if already exists, throw exception on error. public bool PutBlockList(string containerName, string blobName, string[] blockIds) { try { CloudBlobContainer container = BlobClient.GetContainerReference(containerName); CloudBlockBlob blob = container.GetBlockBlobReference(blobName); blob.PutBlockList(blockIds); return true; } catch (StorageClientException ex) { if ((int)ex.StatusCode == 404) { return false; } throw; } }
顯示用PutBlock,PutBlockList上傳10MB單個檔案結果: