使用 Cloud Storage

您可以使用 Cloud Storage 儲存及提供檔案,像是電影、圖片或其他靜態內容等。

本文件說明在應用程式中,如何透過 Google Cloud 用戶端程式庫使用 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/flexible

編輯專案設定並安裝依附元件

app.yaml 中,將您的專案 ID 新增至 GOOGLE_CLOUD_PROJECT 環境值,接著將 GCLOUD_STORAGE_BUCKET 環境值設為您先前建立的 Cloud Storage 值區名稱。

runtime: nodejs
env: flex

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": "ava system-test/*.test.js -T 30s"
  },
  "engines": {
    "node": ">=4.3.2"
  },
  "dependencies": {
    "@google-cloud/storage": "1.6.0",
    "body-parser": "1.18.2",
    "express": "4.16.3",
    "multer": "1.3.0",
    "pug": "2.0.3"
  },
  "devDependencies": {
    "@google-cloud/nodejs-repo-tools": "^2.3.0",
    "ava": "0.25.0"
  },
  "cloud-repo-tools": {
    "requiresProjectId": true,
    "requiresKeyFile": true,
    "test": {
      "app": {
        "requiredEnvVars": [
          "GCLOUD_STORAGE_BUCKET"
        ],
        "msg": "<input type=\"file\" name=\"file\">",
        "substitutions": "YOUR_BUCKET_NAME=$GCLOUD_STORAGE_BUCKET"
      },
      "build": {
        "requiredEnvVars": [
          "GCLOUD_STORAGE_BUCKET"
        ]
      }
    }
  }
}

應用程式的程式碼

應用程式範例會顯示網頁,提示使用者提供要儲存在 Cloud Storage 的檔案。只要使用者選取檔案並按一下 [提交],上傳處理常式就會將檔案內容載入 blob 並寫入 Cloud Storage。

請注意,檔案上傳至 Cloud Storage 後,系統會傳回該檔案的公開網址。您可以利用這個網址直接從 Cloud Storage 提供檔案。建議您將這個值儲存在應用程式中,方便日後使用。

const format = require('util').format;
const express = require('express');
const Multer = require('multer');
const bodyParser = require('body-parser');

// 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 = Storage();

const app = express();
app.set('view engine', 'pug');
app.use(bodyParser.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();

  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 = 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 說明文件

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Node.js 適用的 App Engine 彈性環境文件