arrow_back

アプリ開発 - Cloud Storage への画像ファイルと動画ファイルの保存: Node.js

ログイン 参加
700 以上のラボとコースにアクセス

アプリ開発 - Cloud Storage への画像ファイルと動画ファイルの保存: Node.js

ラボ 2時間 universal_currency_alt クレジット: 5 show_chart 入門
info このラボでは、学習をサポートする AI ツールが組み込まれている場合があります。
700 以上のラボとコースにアクセス

概要

このラボでは、オンライン クイズ アプリケーションを拡張して画像や動画を扱えるようにします。ファイルはオブジェクトとして Cloud Storage バケット内に保存します。

クイズ アプリケーションのユーザー インターフェースが変更され、質問追加用のフォームにファイル用のボタンが追加されており、サーバー側アプリケーションで画像データを受け取れるようにハンドラも変更されています。

ここでは、アップロードされたファイルを Cloud Storage 内に保存するコードを追加します。また、オブジェクトを一般公開してから、オブジェクトの URL とその他のアプリケーション データを Google Cloud Datastore 内に保存します。

目標

このラボでは、次のタスクの実行方法について学びます。

  • Cloud Storage バケットを作成する。

  • ファイル アップロード用の UI とコードの変更内容を確認する。

  • アップロードされたファイルのデータを Cloud Storage に保存するコードを記述する。

設定と要件

各ラボでは、新しい Google Cloud プロジェクトとリソースセットを一定時間無料で利用できます。

  1. Qwiklabs にシークレット ウィンドウでログインします。

  2. ラボのアクセス時間(例: 1:15:00)に注意し、時間内に完了できるようにしてください。
    一時停止機能はありません。必要な場合はやり直せますが、最初からになります。

  3. 準備ができたら、[ラボを開始] をクリックします。

  4. ラボの認証情報(ユーザー名パスワード)をメモしておきます。この情報は、Google Cloud Console にログインする際に使用します。

  5. [Google Console を開く] をクリックします。

  6. [別のアカウントを使用] をクリックし、このラボの認証情報をコピーしてプロンプトに貼り付けます。
    他の認証情報を使用すると、エラーが発生したり、料金の請求が発生したりします。

  7. 利用規約に同意し、再設定用のリソースページをスキップします。

Google Cloud Shell の有効化

Google Cloud Shell は、開発ツールと一緒に読み込まれる仮想マシンです。5 GB の永続ホーム ディレクトリが用意されており、Google Cloud で稼働します。

Google Cloud Shell を使用すると、コマンドラインで Google Cloud リソースにアクセスできます。

  1. Google Cloud コンソールで、右上のツールバーにある [Cloud Shell をアクティブにする] ボタンをクリックします。

  2. [続行] をクリックします。

環境がプロビジョニングされ、接続されるまでしばらく待ちます。接続した時点で認証が完了しており、プロジェクトに各自のプロジェクト ID が設定されます。次に例を示します。

gcloud は Google Cloud のコマンドライン ツールです。このツールは、Cloud Shell にプリインストールされており、タブ補完がサポートされています。

  • 次のコマンドを使用すると、有効なアカウント名を一覧表示できます。
gcloud auth list

出力:

Credentialed accounts: - @.com (active)

出力例:

Credentialed accounts: - google1623327_student@qwiklabs.net
  • 次のコマンドを使用すると、プロジェクト ID を一覧表示できます。
gcloud config list project

出力:

[core] project =

出力例:

[core] project = qwiklabs-gcp-44776a13dea667a6 注: gcloud ドキュメントの全文については、 gcloud CLI の概要ガイド をご覧ください。

ケーススタディ用アプリケーションを確認する

このセクションでは、クイズ アプリケーションが格納されている Git リポジトリのクローンを作成し、このアプリケーションを実行します。

Cloud Shell でソースコードのクローンを作成する

  1. Cloud Shell で、クラスのリポジトリのクローンを作成します。

git clone --depth=1 https://github.com/GoogleCloudPlatform/training-data-analyst
  1. 作業ディレクトリへのショートカットとしてソフトリンクを作成します。

ln -s ~/training-data-analyst/courses/developingapps/v1.3/nodejs/cloudstorage cloudstorage

ケーススタディ用アプリケーションを構成、実行する

  1. このラボのサンプル ファイルが格納されているディレクトリに移動します。

cd ~/cloudstorage/start
  1. 次のコマンドを実行して、アプリケーションを構成します。

. prepare_environment.sh
  1. 次のコマンドを実行して、アプリケーションを実行します。

npm start

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 ケーススタディ用アプリケーションを構成する

ケーススタディ用アプリケーションを確認する

  1. 「ウェブでプレビュー」アイコン > [ポート 8080 でプレビュー] をクリックして、アプリケーションを表示します。

  1. ツールバーの [Create Question] をクリックします。

ケーススタディ用アプリケーションのコードを確認する

このセクションでは、Cloud Shell テキスト エディタを使用して、このケーススタディ用アプリケーションのコードを確認します。

Cloud Shell エディタを起動する

  1. Cloud Shell で [エディタを開く] をクリックし、[新しいウィンドウで開く] をクリックします。

  1. エディタの左側にあるファイル ブラウザ パネルを使用して、/cloudstorage/start フォルダに移動します。

Express ウェブ アプリケーションを確認する

  1. .../server/web-app/views/questions フォルダにある [add.pug] ファイルを選択します。
  1. .../server/web-app フォルダにある [questions.js] ファイルを選択します。
  1. .../server/gcp/cloudstorage.js ファイルを選択します。

Cloud Storage バケットを作成する

このセクションでは、Cloud Storage バケットを作成し、それを参照する環境変数をエクスポートします。

Cloud Storage バケットを作成する

  1. Cloud Shell に戻って [ターミナルを開く] をクリックし、Ctrl+C キーを押してアプリケーションを停止します。

  2. 次のコマンドを実行して、<プロジェクト ID>-media という名前の Cloud Storage バケットを作成します。

gsutil mb gs://$DEVSHELL_PROJECT_ID-media
  1. 次のコマンドを実行して、Cloud Storage バケット名を GCLOUD_BUCKET という名前の環境変数としてエクスポートします。

export GCLOUD_BUCKET=$DEVSHELL_PROJECT_ID-media

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 Cloud Storage バケットを作成する

Cloud Storage にオブジェクトを追加する

このセクションでは、アップロードされたファイルを Cloud Storage に保存するコードを記述します。

Node.js の Cloud Storage モジュールをインポートして使用する

  1. エディタで、...server/gcp/cloudstorage.js ファイルの先頭に移動します。

  2. @google-cloud/storage モジュールを読み込み、Storage という名前の定数に割り当てます。

  3. // TODO: Load the module for Cloud Storage const {Storage} = require('@google-cloud/storage'); // END TODO
  4. Storage(...) ファクトリを使用して、storage という名前の Cloud Storage クライアントを作成します。

  5. // TODO: Create the storage client // The Storage(...) factory function accepts an options // object which is used to specify which project's Cloud // Storage buckets should be used via the projectId // property. // The projectId is retrieved from the config module. // This module retrieves the project ID from the // GCLOUD_PROJECT environment variable. const storage = new Storage({ projectId: config.get('GCLOUD_PROJECT') }); // END TODO
  6. GCLOUD_BUCKET という名前の文字列定数を宣言し、環境変数として先ほどエクスポートしたバケット名で初期化します。

  7. // TODO: Get the GCLOUD_BUCKET environment variable // Recall that earlier you exported the bucket name into an // environment variable. // The config module provides access to this environment // variable so you can use it in code const GCLOUD_BUCKET = config.get('GCLOUD_BUCKET'); // END TODO
  8. bucket という名前の定数を宣言して、Cloud Storage バケットを参照します。

  9. // TODO: Get a reference to the Cloud Storage bucket const bucket = storage.bucket(GCLOUD_BUCKET); // END TODO

Cloud Storage にファイルを送信するコードを記述する

sendUploadToGCS(req, res, next) ハンドラで、Cloud Storage クライアントを使用して Cloud Storage バケットにファイルをアップロードし、一般公開します。

  1. バケット内の Cloud Storage の file オブジェクトへの参照を取得します。

  2. // TODO: Get a reference to the new object const file = bucket.file(oname); // END TODO
  3. Cloud Storage オブジェクトにデータを送信するための書き込み可能なストリームを作成し、オブジェクトの MIME タイプを渡します。

  4. // TODO: Create a stream to write the file into // Cloud Storage // The uploaded file's MIME type can be retrieved using // req.file.mimetype. // Cloud Storage metadata can be used for many purposes, // including establishing the type of an object. const stream = file.createWriteStream({ metadata: { contentType: req.file.mimetype } }); // END TODO
  5. ストリームにイベント ハンドラを 2 つ追加します。1 つ目のハンドラでエラーを処理します。2 つ目のハンドラはデータのアップロード終了時に呼び出します。

    エラー処理用のイベント ハンドラで、次に処理する Express ミドルウェアを呼び出します。

  6. // TODO: Attach two event handlers (1) error // Event handler if there's an error when uploading stream.on('error', err => { // TODO: If there's an error move to the next handler next(err); // END TODO }); // END TODO
  7. 終了時のイベント ハンドラで、ファイルを一般公開し、新しい公開 URL を参照する新しいプロパティを Datastore エンティティに設定します。

  8. // TODO: Attach two event handlers (2) finish // The upload completed successfully stream.on('finish', () => { // TODO: Make the object publicly accessible file.makePublic().then(() => { // TODO: Set a new property on the file for the // public URL for the object // Cloud Storage public URLs are in the form: // https://storage.googleapis.com/[BUCKET]/[OBJECT] // Use an ECMAScript template literal (`https://...`)to // populate the URL with appropriate values for the bucket // ${GCLOUD_BUCKET} and object name ${oname} req.file.cloudStoragePublicUrl = `https://storage.googleapis.com/${GCLOUD_BUCKET}/${oname}`; // END TODO // TODO: Invoke the next middleware handler next(); // END TODO }); // END TODO }); // END TODO
  9. sendUploadToGCS(req, res, next) ハンドラの最後で、ファイルのデータを Cloud Storage にアップロードするために、end() メソッドを呼び出してファイルをストリームに書き込みます

  10. // TODO: End the stream to upload the file's data stream.end(req.file.buffer); // END TODO

cloudstorage.js

上記の変更をして、ファイルは次のようになります:

'use strict'; const config = require('../config'); // TODO: Load the module for Cloud Storage const {Storage} = require('@google-cloud/storage'); // END TODO // TODO: Create the storage client // The Storage(...) factory function accepts an options // object which is used to specify which project's Cloud // Storage buckets should be used via the projectId // property. // The projectId is retrieved from the config module. // This module retrieves the project ID from the // GCLOUD_PROJECT environment variable. const storage = new Storage({ projectId: config.get('GCLOUD_PROJECT') }); // END TODO // TODO: Get the GCLOUD_BUCKET environment variable // Recall that earlier you exported the bucket name into an // environment variable. // The config module provides access to this environment // variable so you can use it in code const GCLOUD_BUCKET = config.get('GCLOUD_BUCKET'); // END TODO // TODO: Get a reference to the Cloud Storage bucket const bucket = storage.bucket(GCLOUD_BUCKET); // END TODO // Express middleware that will automatically pass uploads to Cloud Storage. // req.file is processed and will have a new property: // * ``cloudStoragePublicUrl`` the public url to the object. // [START sendUploadToGCS] function sendUploadToGCS(req, res, next) { // The existing code in the handler checks to see if there // is a file property on the HTTP request - if a file has // been uploaded, then Multer will have created this // property in the preceding middleware call. if (!req.file) { return next(); } // In addition, a unique object name, oname, has been // created based on the file's original name. It has a // prefix generated using the current date and time. // This should ensure that a new file upload won't // overwrite an existing object in the bucket const oname = Date.now() + req.file.originalname; // TODO: Get a reference to the new object const file = bucket.file(oname); // END TODO // TODO: Create a stream to write the file into // Cloud Storage // The uploaded file's MIME type can be retrieved using // req.file.mimetype. // Cloud Storage metadata can be used for many purposes, // including establishing the type of an object. const stream = file.createWriteStream({ metadata: { contentType: req.file.mimetype } }); // END TODO // TODO: Attach two event handlers (1) error // Event handler if there's an error when uploading stream.on('error', err => { // TODO: If there's an error move to the next handler next(err); // END TODO }); // END TODO // TODO: Attach two event handlers (2) finish // The upload completed successfully stream.on('finish', () => { // TODO: Make the object publicly accessible file.makePublic().then(() => { // TODO: Set a new property on the file for the // public URL for the object // Cloud Storage public URLs are in the form: // https://storage.googleapis.com/[BUCKET]/[OBJECT] // Use an ECMAScript template literal (`https://...`)to // populate the URL with appropriate values for the bucket // ${GCLOUD_BUCKET} and object name ${oname} req.file.cloudStoragePublicUrl = `https://storage.googleapis.com/${GCLOUD_BUCKET}/${oname}`; // END TODO // TODO: Invoke the next middleware handler next(); // END TODO }); // END TODO }); // END TODO // TODO: End the stream to upload the file's data stream.end(req.file.buffer); // END TODO } // [END sendUploadToGCS] // Multer handles parsing multipart/form-data requests. // This instance is configured to store images in memory. // This makes it straightforward to upload to Cloud Storage. // [START multer] const Multer = require('multer'); const multer = Multer({ storage: Multer.MemoryStorage, limits: { fileSize: 40 * 1024 * 1024 // no larger than 40mb } }); // [END multer] module.exports = { sendUploadToGCS, multer };

アプリケーションを実行し、Cloud Storage オブジェクトを作成する

  1. ...server/gcp/cloudstorage.js ファイルを保存し、Cloud Shell コマンドに戻ります。
  2. npm start」と入力して、アプリケーションを開始します。
  3. この画像ファイルをローカルマシンにダウンロードします。
  4. Cloud Shell で「ウェブでプレビュー」アイコン > [ポート 8080 でプレビュー] をクリックし、クイズ アプリケーションをプレビューします。
  5. [Create Question] をクリックします。
  6. フォームに次の値を入力して、[Save] をクリックします。

フォームの項目

Author

[自分の名前]

Quiz

Google Cloud Platform

Title

Which product does this logo relate to?

画像

先ほどダウンロードした Google-Cloud-Storage-Logo.svg ファイルをアップロードします

Answer 1

App Engine

Answer 2

Cloud Storage([Answer 2] のラジオボタンを選択します)

Answer 3

Compute Engine

Answer 4

Container Engine

  1. Cloud Console に戻り、ナビゲーション メニュー > [Cloud Storage] をクリックします。
  2. [Cloud Storage] > [ブラウザ] ページで、適切なバケット(<プロジェクト ID>-media という名前)をクリックします。

[進行状況を確認] をクリックして、目標に沿って進んでいることを確認します。 アプリケーションを実行し、Cloud Storage オブジェクトを作成する

クライアント アプリケーションを実行し、Cloud Storage の公開 URL をテストする

  1. アプリケーションの URL の末尾に /api/quizzes/gcp を追加します。
  1. アプリケーションのホームページに戻り、[Take Test] をクリックします。
  2. [GCP] をクリックし、各質問に答えます。

ラボを終了する

ラボが完了したら、[ラボを終了] をクリックします。ラボで使用したリソースが Google Cloud Skills Boost から削除され、アカウントの情報も消去されます。

ラボの評価を求めるダイアログが表示されたら、星の数を選択してコメントを入力し、[送信] をクリックします。

星の数は、それぞれ次の評価を表します。

  • 星 1 つ = 非常に不満
  • 星 2 つ = 不満
  • 星 3 つ = どちらともいえない
  • 星 4 つ = 満足
  • 星 5 つ = 非常に満足

フィードバックを送信しない場合は、ダイアログ ボックスを閉じてください。

フィードバックやご提案の送信、修正が必要な箇所をご報告いただく際は、[サポート] タブをご利用ください。

Copyright 2020 Google LLC All rights reserved. Google および Google のロゴは Google LLC の商標です。その他すべての企業名および商品名はそれぞれ各社の商標または登録商標です。

始める前に

  1. ラボでは、Google Cloud プロジェクトとリソースを一定の時間利用します
  2. ラボには時間制限があり、一時停止機能はありません。ラボを終了した場合は、最初からやり直す必要があります。
  3. 画面左上の [ラボを開始] をクリックして開始します

このコンテンツは現在ご利用いただけません

利用可能になりましたら、メールでお知らせいたします

ありがとうございます。

利用可能になりましたら、メールでご連絡いたします

1 回に 1 つのラボ

既存のラボをすべて終了して、このラボを開始することを確認してください

シークレット ブラウジングを使用してラボを実行する

このラボの実行には、シークレット モードまたはシークレット ブラウジング ウィンドウを使用してください。これにより、個人アカウントと受講者アカウントの競合を防ぎ、個人アカウントに追加料金が発生することを防ぎます。