使用 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 中,将您的项目 ID 添加到 GOOGLE_CLOUD_PROJECT 环境值中。然后将 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 后,系统会返回该文件的公共网址,您可以使用该网址直接从 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 文档