【问题标题】:Loading an image from Google Cloud Bucket with PHP使用 PHP 从 Google Cloud Bucket 加载图像
【发布时间】:2019-11-20 11:05:25
【问题描述】:

是否可以以类似于 file_get_contents 的方式从谷歌云存储桶获取图像?我需要将图像弄乱,而无需将其放在本地机器/服务器上

我曾尝试使用 php 的谷歌云存储库 (https://github.com/googleapis/google-cloud-php-storage),但它一直给我“无法打开流”错误,这让我相信我可能为 file_get_content 函数提供了错误的 url。

我应该提一下,所有文件都设置为公开,并提供公共 storage.cloud.google.com 链接

我现在的代码是这样的:

require 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient();
$storage->registerStreamWrapper();

$contents = file_get_contents('gs://{BUCKET}/{IMAGE NAME}.jpg');

虽然我目前的存储桶结构更像这样

存储桶 - 文件夹 - 图片

我尝试在 URL 中添加文件夹,但它仍然给我同样的“无法打开流”错误。谁能指出我做错了什么?我需要进行身份验证吗?我什至需要图书馆吗?我尝试使用 file_get_content($public_url) 但由于 storage.cloud.google.com 链接会重定向您,这显然不起作用哈哈哈

任何帮助将不胜感激

干杯

【问题讨论】:

    标签: php google-cloud-storage


    【解决方案1】:

    我已安装 Cloud SDK,并使用默认服务帐户凭据连接到 Google Cloud 服务link

    一般来说,Google Cloud PHP 库使用 Service Account 连接到 Google Cloud 服务的凭据。运行时 Compute Engine 将自动发现凭据。什么时候 在其他环境中运行,服务帐户凭据可以是 通过提供账户的 JSON 密钥文件的路径来指定 (或 JSON 本身)在环境变量中。

    1. 运行composer require google/cloud

    2. 创建一个 test.php 文件:

      <?php
      # Includes the autoloader for libraries installed with composer
      require __DIR__ . '/vendor/autoload.php';
      
      # Imports the Google Cloud client library
      use Google\Cloud\Storage\StorageClient;
      
      # Your Google Cloud Platform project ID
      $projectId = 'my_project';
      
      # Instantiates a client
      $storage = new StorageClient([
      'projectId' => $projectId
      ]);
      
      # The name for the new bucket
      $storage->registerStreamWrapper();
      
      $contents = file_get_contents('gs://my-buck-sample/image.JPG');
      
      echo 'content' . $contents . ' created.';
      ?>
      

    3.运行php test.php

    【讨论】:

    • 谢谢!问题是我还没有添加服务密钥
    猜你喜欢
    • 2018-06-06
    • 2017-11-08
    • 2020-02-17
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多