Cloud Storage の使用

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

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

始める前に

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

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

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

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

サンプルのダウンロード

リポジトリのクローンを作成するには、次のコマンドを実行します。

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples/
cd nodejs-docs-samples/appengine/storage/standard

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

app.yaml で、GOOGLE_CLOUD_PROJECT 環境値にプロジェクト ID を追加します。GCLOUD_STORAGE_BUCKET 環境値には作成済みの Cloud Storage バケットの名前を設定します。

runtime: nodejs16

env_variables:
  GCLOUD_STORAGE_BUCKET: YOUR_BUCKET_NAME

package.json 内に、依存関係として @google-cloud/storage を追加します。これで Cloud Storage を利用するための機能が提供されます。

{
  "name": "appengine-storage",
  "description": "Node.js Google Cloud Storage sample for Google App Engine",
  "scripts": {
    "start": "node app.js",
    "test": "mocha system-test/*.test.js --exit --timeout=30000"
  },
  "engines": {
    "node": ">=14.0.0"
  },
  "dependencies": {
    "@google-cloud/storage": "^6.0.0",
    "express": "^4.17.1",
    "multer": "^1.4.2",
    "pug": "^3.0.0"
  },
  "devDependencies": {
    "mocha": "^9.0.0",
    "supertest": "^6.0.0",
    "proxyquire": "^2.1.3"
  }
}

ローカルでの実行とテストの手順については、README.md ファイルをご覧ください。

アプリケーション コード

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

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

const {format} = require('util');
const express = require('express');
const Multer = require('multer');

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GOOGLE_CLOUD_PROJECT environment variable. See
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// These environment variables are set automatically on Google App Engine
const {Storage} = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

const app = express();
app.set('view engine', 'pug');

// This middleware is available in Express v4.16.0 onwards
app.use(express.json());

// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
  },
});

// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);

// Display a form for uploading files.
app.get('/', (req, res) => {
  res.render('form.pug');
});

// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream({
    resumable: false,
  });

  blobStream.on('error', err => {
    next(err);
  });

  blobStream.on('finish', () => {
    // The public URL can be used to directly access the file via HTTP.
    const publicUrl = format(
      `https://storage.googleapis.com/${bucket.name}/${blob.name}`
    );
    res.status(200).send(publicUrl);
  });

  blobStream.end(req.file.buffer);
});

const PORT = parseInt(process.env.PORT) || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

詳細情報

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