.

iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0

Azure Blob 儲存體文件

我們在使用 Webapp 應用服務時,
需要有個一空間存放使用者上傳的檔案,
Azure 提供 Blob 儲存體服務。
Azure Blob 儲存體文件

Azure Blob 儲存體是 Microsoft 針對雲端推出的物件儲存體解決方案

Azure Blob 儲存體簡介

Blob 儲存體設計用來:

  • 直接提供映像或文件給瀏覽器。
  • 儲存檔案供分散式存取。
  • 串流傳輸視訊和音訊。
  • 寫入記錄檔。
  • 儲存備份和還原、災害復原和封存資料。
  • 儲存資料供內部部署或 Azure 託管服務進行分析。

Blob 儲存體提供三種類型資源:

  • 儲存體帳戶
  • 儲存體帳戶中的容器
  • 容器中的 Blob

https://docs.microsoft.com/zh-tw/azure/storage/blobs/media/storage-blobs-introduction/blob1.png

區塊 Blob 價格

由官網定價說明, 前 50 TB / 月 經常性存取 每 GB NT$0.6011
也就是說,如果我們用10G的空間,每月要付 6 元的儲存費
https://ithelp.ithome.com.tw/upload/images/20200927/200726511RUDnxNxof.png

當然還有另外的傳輸費用
https://ithelp.ithome.com.tw/upload/images/20200927/20072651wSsSzbESHO.png
https://ithelp.ithome.com.tw/upload/images/20200927/20072651f6eh0tjOw1.png

創建 Azure Storage

建立儲存體帳戶

Azure 儲存體帳戶包含您所有的 Azure 儲存體資料物件:Blob、檔案、佇列、資料表和磁碟。 儲存體帳戶會為您的 Azure 儲存體資料提供唯一的命名空間,此命名空間可透過 HTTP 或 HTTPS 從世界各地存取。

查看 az storage 指令

az storage -h

https://ithelp.ithome.com.tw/upload/images/20200927/2007265182PLPYYjCX.png

查看 az storage account 說明

az storage account -h

https://ithelp.ithome.com.tw/upload/images/20200927/20072651Ed0GXpPXUH.png
https://ithelp.ithome.com.tw/upload/images/20200927/20072651IzvRNOhUzZ.png

創建 storage account

儲存體名稱: pellokstorage
資源群組: PellokIThomePipelineRG
位於: eastasia
SKU資源: Standard_LRS
類型: StorageV2

az storage account create \
    --name pellokstorage \
    --resource-group PellokIThomePipelineRG \
    --location eastasia \
    --sku Standard_LRS \
    --kind StorageV2
複寫選項 sku 參數
本機備援儲存體 (LRS) Standard_LRS
區域備援儲存體 (ZRS) Standard_ZRS
異地備援儲存體 (GRS) Standard_GRS
讀取權限異地備援儲存體 (GRS) Standard_RAGRS
異地區域備援儲存體 (GZRS Standard_GZRS
讀取權限異地區域備援儲存體 (RA-GZRS) Standard_RAGZRS

https://ithelp.ithome.com.tw/upload/images/20200927/20072651ZNTf7AQSlw.png

上傳檔案到 Azure Blob 儲存體

實作快速入門:適用於 .NET 的 Azure Blob 儲存體用戶端程式庫 v12

建立專案

dotnet new console -n PellokITHomeBlob
cd PellokITHomeBlob
mkdir data

https://ithelp.ithome.com.tw/upload/images/20200927/20072651hIKWqHb8q3.png

安裝套件

dotnet add package Azure.Storage.Blobs

https://ithelp.ithome.com.tw/upload/images/20200927/200726513FgnipzbEF.png

設定應用程式架構

編輯 Program.cs 檔案
增加 using Azure.Storage.Blobs
修改 Main()

using System;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.IO;
using System.Threading.Tasks;

namespace PellokITHomeBlob
{
    class Program
    {
        static async Task Main()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

取得 Storage Account 的 連接字串

az storage account show-connection-string -g PellokIThomePipelineRG -n pellokstorage

https://ithelp.ithome.com.tw/upload/images/20200927/20072651yKvFhuLU7x.png

設定儲存體連接字串

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

取得連接字串

string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

建立容器

// 創建 BlobServiceClient 
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

// 設定 containerName
string containerName = "pellokblobs" + Guid.NewGuid().ToString();

// 創建 BlobContainerClient
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

將 Blob 上傳至容器

// 創建檔案
string localPath = "./data/";
string fileName = "pellok" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);

// 在檔案內寫入資料
await File.WriteAllTextAsync(localFilePath, "Hello, World!");

// 取得 BlobClient
BlobClient blobClient = containerClient.GetBlobClient(fileName);

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

// 開啟FileStream,上傳檔案,關閉FileStream
using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();

列出容器中的 Blob

Console.WriteLine("Listing blobs...");

// 列出 Blob 內的檔案
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
    Console.WriteLine("\t" + blobItem.Name);
}

下載 Blob

// 下載檔案後面的.txt副檔名 取代為 DOWNLOADED.txt
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

// 下載檔案
BlobDownloadInfo download = await blobClient.DownloadAsync();

using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
    await download.Content.CopyToAsync(downloadFileStream);
    downloadFileStream.Close();
}

刪除容器

// 刪除確認
Console.Write("Press any key to begin clean up");
Console.ReadLine();

Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();

Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);

Console.WriteLine("Done");

檔案原始碼

using System;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.IO;
using System.Threading.Tasks;

namespace PellokITHomeBlob
{
    class Program
    {
        static async Task Main()
        {
            Console.WriteLine("Hello World!");

            // 取得連線字串
            string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

            // 創建 BlobServiceClient 
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            // 設定 containerName
            string containerName = "pellokblobs" + Guid.NewGuid().ToString();

            // 創建 BlobContainerClient
            BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

            // 創建檔案
            string localPath = "./data/";
            string fileName = "pellok" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            // 在檔案內寫入資料
            await File.WriteAllTextAsync(localFilePath, "Hello, World!");

            // 取得 BlobClient
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            // 開啟FileStream,上傳檔案,關閉FileStream
            using FileStream uploadFileStream = File.OpenRead(localFilePath);
            await blobClient.UploadAsync(uploadFileStream, true);
            uploadFileStream.Close();

            Console.WriteLine("Listing blobs...");

            // 列出 Blob 內的檔案
            await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
            {
                Console.WriteLine("\t" + blobItem.Name);
            }

            // 下載檔案後面的.txt副檔名 取代為 DOWNLOADED.txt
            string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

            Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

            // 下載檔案
            BlobDownloadInfo download = await blobClient.DownloadAsync();

            using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
            {
                await download.Content.CopyToAsync(downloadFileStream);
                downloadFileStream.Close();
            } 

            // 刪除確認
            Console.Write("Press any key to begin clean up");
            Console.ReadLine();

            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Deleting the local source and downloaded files...");
            File.Delete(localFilePath);
            File.Delete(downloadFilePath);

            Console.WriteLine("Done");

        }
    }
}

執行程式碼

dotnet build

https://ithelp.ithome.com.tw/upload/images/20200927/20072651yQzA0Ea4Bt.png

dotnet run

https://ithelp.ithome.com.tw/upload/images/20200927/20072651htq0hohl3E.png

驗證
https://ithelp.ithome.com.tw/upload/images/20200927/20072651eiVBYv15AQ.png

在點擊一下刪除 Blob

相關連結:

上一篇 Day26 Azure Container Registry (ACR)服務
下一篇 Day28 Azure Cache for Redis 服務


上一篇
Day26 Azure Container Registry (ACR)服務
下一篇
Day28 Azure Cache for Redis 服務
系列文
Azure 的自我修煉30
.
圖片
  直播研討會

尚未有邦友留言

立即登入留言