Cloud Storage の使用

Cloud Storage は、ファイル(動画、画像、その他の静的コンテンツなど)を保存または提供する目的で使用できます。

このドキュメントでは、アプリで Google Cloud クライアント ライブラリを使用して、Cloud Storage にデータを格納したり、Cloud Storage からデータを取得したりする方法を説明します。

始める前に

  • App Engine の .NET 用「Hello, World!」の説明に従って環境とプロジェクトを設定し、App Engine での .NET アプリの構造を理解してください。このドキュメントで説明しているサンプルアプリを実行する際に必要となるため、プロジェクト ID をメモして保存しておきます。

  • 次のコマンドを呼び出して、アプリケーション用の Cloud Storage バケットを作成します。

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • バケットを一般公開(読み取り可能)にして、ファイルを提供できるようにします。

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    
  • アプリケーションをローカルで実行するには、サービス アカウントを設定して、認証情報をダウンロードします。

    1. Google Cloud Console で認証情報のリストを開きます。

      認証情報のリストを開く

    2. [認証情報を作成] をクリックします。

    3. [サービス アカウント キー] を選択します。

      [サービス アカウントキーの作成] ウィンドウが開きます。

    4. [サービス アカウント] の下にあるプルダウン ボックスをクリックし、[Compute Engine のデフォルトのサービス アカウント] をクリックします。

    5. JSONキーのタイプを選択します。

    6. [作成] をクリックします。

      新しい秘密鍵ウィンドウが表示され、秘密鍵が自動的にダウンロードされます。

    7. [閉じる] をクリックします。

    8. 環境変数 GOOGLE_APPLICATION_CREDENTIALS を、ダウンロードした JSON キーのパスに設定します。次に示すのは、PowerShell での例です。

      # For this powershell session.
      PS > $env:GOOGLE_APPLICATION_CREDENTIALS = "$env:USERPROFILE\Downloads\your-project-id-dea9fa230eae3.json"
      # For all processes created after this command.
      PS > [Environment]::SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "$env:USERPROFILE\Downloads\your-project-id-dea9fa230eae3.json", "User")
      

サンプルのダウンロード

  1. サンプルアプリをダウンロードして抽出します。

  2. コマンドラインを使用する場合は、app ディレクトリに移動して、dotnet-docs-samples\appengine\flexible\ を実行します。

プロジェクト構成の編集と依存関係のインストール

appsettings.jsonBucketName を設定します。この値は、以前に作成した Cloud Storage バケットの名前です。

{
  "GoogleCloudStorage": {
    "BucketName": "your-google-bucket-name"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

アプリケーション コード

このサンプル アプリケーションはウェブページを表示し、Cloud Storage に保存するファイルを指定するようユーザーに促します。ユーザーがファイルを選択して [送信] をクリックすると、アップロード ハンドラがファイルの内容を blob に読み込み、Cloud Storage に書き込みます。

ファイルが Cloud Storage にアップロードされると、このファイルの公開 URL が返されます。この URL を使用して、Cloud Storage から直接ファイルを配信できます。今後も使用できるように、この値をアプリで保存してください。

    public class HomeController : Controller
    {
        // Contains the bucket name and object name
        readonly CloudStorageOptions _options;
        // The Google Cloud Storage client.
        readonly StorageClient _storage;

        public HomeController(IOptions<CloudStorageOptions> options)
        {
            _options = options.Value;
            _storage = StorageClient.Create();
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var model = new HomeIndex();
            if (new string[] { null, "", "your-google-bucket-name" }
                .Contains(_options.BucketName))
            {
                model.MissingBucketName = true;
                return View(model);
            }
            try
            {
                // Get the storage object.
                var storageObject =
                    await _storage.GetObjectAsync(_options.BucketName, _options.ObjectName);
                // Get a direct link to the storage object.
                model.MediaLink = storageObject.MediaLink;
                // Download the storage object.
                MemoryStream m = new MemoryStream();
                await _storage.DownloadObjectAsync(
                    _options.BucketName, _options.ObjectName, m);
                m.Seek(0, SeekOrigin.Begin);
                byte[] content = new byte[m.Length];
                m.Read(content, 0, content.Length);
                model.Content = Encoding.UTF8.GetString(content);
            }
            catch (GoogleApiException e)
            when (e.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
            {
                // Does not exist yet.  No problem.
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Index(Form sendForm)
        {
            var model = new HomeIndex();
            // Take the content uploaded in the form and upload it to
            // Google Cloud Storage.
            await _storage.UploadObjectAsync(
                _options.BucketName, _options.ObjectName, "text/plain",
                new MemoryStream(Encoding.UTF8.GetBytes(sendForm.Content)));
            model.Content = sendForm.Content;
            model.SavedNewContent = true;
            var storageObject =
                await _storage.GetObjectAsync(_options.BucketName, _options.ObjectName);
            model.MediaLink = storageObject.MediaLink;
            return View(model);
        }

詳細情報

Cloud Storage の詳細については、Cloud Storage のドキュメントをご覧ください。