使用 Cloud Storage

您可以使用 Cloud Storage 来存储和提供文件,例如电影、图片或其他静态内容。

本文档介绍了如何在应用中使用适用于 Cloud Storage 的 Cloud 客户端库存储数据以及从 Cloud Storage 检索数据。

准备工作

  • 按照设置开发环境中的说明设置您的环境和项目,并了解如何在 App Engine 中设计应用的结构。记录并保存项目 ID,因为您需要用它来运行本文档中介绍的示例应用。
  • 请务必调用以下命令,为您的应用创建 Cloud Storage 存储桶:

          gcloud storage buckets create gs://YOUR_BUCKET_NAME
    
  • 将此存储桶设为可公开读取,以便其可以传送文件:

          gcloud storage buckets add-iam-policy-binding gs://<var>YOUR_BUCKET_NAME</var> --member=allUsers --role=roles/storage.objectViewer
    

下载示例

Go

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/golang-samples.git
cd golang-samples/appengine_flexible/storage

Java

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/java-docs-samples
cd java-docs-samples/flexible/java-17/cloudstorage

Node.js

如需克隆代码库,请执行以下命令:

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

PHP

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/php-docs-samples
cd php-docs-samples/appengine/flexible/storage

Python

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/appengine/flexible/storage

Ruby

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples
cd ruby-docs-samples/appengine/flexible/storage/

.NET

  1. 下载示例应用并将其解压缩。

  2. 如果您使用的是命令行,请找到以下应用目录:

        dotnet-docs-samples\appengine\flexible\CloudStorage\CloudStorage.Sample
    

如需在本地运行您的应用,请设置服务账号并下载凭据:

  1. 在 Google Cloud 控制台中打开凭证列表。

    打开凭据列表

  2. 点击创建凭据

  3. 选择服务账号密钥

    此时会打开“创建服务账号密钥”窗口。

  4. 点击服务账号列表,然后选择Compute Engine 默认服务账号

  5. 选择 JSON 作为密钥类型

  6. 点击创建

    此时,系统会显示新建私钥窗口,并自动下载与您所选密钥类型相对应的私钥。

  7. 点击关闭

修改项目配置并安装依赖项

Go

app.yaml 中设置 GCLOUD_STORAGE_BUCKET。此值是您之前创建的 Cloud Storage 存储桶的名称。

# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: go
env: flex

runtime_config:
  operating_system: ubuntu22
  runtime_version: 1.21

automatic_scaling:
  min_num_instances: 1

env_variables: