使用 Cloud Storage

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

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

准备工作

  • 请按照 App Engine 上的 PHP 版“Hello, World!”中的说明设置您的环境和项目,并了解 App Engine 中的 PHP 应用的结构。请记录并保存项目 ID,因为您需要用它来运行本文档中介绍的示例应用。

  • 请务必调用以下命令,为您的应用创建 Cloud Storage 存储分区:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 将此存储分区设为可公开读取,以便其可以传送文件:

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

下载示例

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

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

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

app.yaml 中设置 CLOUD_STORAGE_BUCKET;此值是您之前创建的 Cloud Storage 存储分区的名称。

env_variables:
  GOOGLE_STORAGE_BUCKET: "your-bucket-name"

请注意,您必须在 composer.json 文件中添加 Cloud 客户端库,因为该库提供 Cloud Storage 功能。

{
    "require": {
        "slim/slim": "^4.0",
        "slim/psr7": "^1.3",
        "google/cloud-storage": "^1.0",
        "php-di/slim-bridge": "^3.1"
    }
}

应用代码

示例应用会显示一个网页,提示用户选择要存储在 Cloud Storage 中的文件。用户选择文件并点击“提交”后,上传处理程序会将文件内容加载到 Blob 中并将其写入 Cloud Storage。

请注意,在文件上传到 Cloud Storage 后,系统会返回该文件的公共网址,您可以使用该网址直接从 Cloud Storage 传送该文件。您应将此值存储在应用中以备将来使用。

use DI\Container;
use Google\Cloud\Storage\StorageClient;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Factory\AppFactory;

// Create App
AppFactory::setContainer($container = new Container());
$app = AppFactory::create();

// Display errors
$app->addErrorMiddleware(true, true, true);

$container = $app->getContainer();

$app->get('/', function (Request $request, Response $response) use ($container) {
    /** @var Google\Cloud\StorageClient */
    $storage = $container->get('storage');
    $bucketName = $container->get('bucket_name');
    $objectName = $container->get('object_name');
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $content = $object->exists() ? $object->downloadAsString() : '';
    $escapedContent = htmlspecialchars($content);
    $response->getBody()->write(<<<EOF
    <h1>Storage Example</h1>
    <h3>Write [<a href="https://cloud.google.com/appengine/docs/flexible/php/using-cloud-storage">docs</a>]:</h3>
    <form action="/write" method="post">
        Some file content:<br />
        <textarea name="content"></textarea><br />
        <input type="submit" />
    </form>
EOF
    );
    if ($content) {
        $response->getBody()->write(
            "<p><strong>Your content:</strong><p><p>$escapedContent</p>"
        );
    }
    return $response;
});

/**
 * Write to a Storage bucket.
 * @see https://cloud.google.com/appengine/docs/flexible/php/using-cloud-storage
 */
$app->post('/write', function (Request $request, Response $response) use ($container) {
    /** @var Google\Cloud\StorageClient */
    $storage = $container->get('storage');
    $bucketName = $container->get('bucket_name');
    $objectName = $container->get('object_name');
    parse_str((string) $request->getBody(), $postData);
    $metadata = ['contentType' => 'text/plain'];
    $storage->bucket($bucketName)->upload($postData['content'] ?? '', [
        'name' => $objectName,
        'metadata' => $metadata,
    ]);
    return $response
        ->withStatus(302)
        ->withHeader('Location', '/');
});

$container->set('storage', function () use ($container) {
    $projectId = $container->get('project_id');
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    return $storage;
});

了解详情

如需全面了解 Cloud Storage,请参阅 Cloud Storage 文档