【问题标题】:Get all Folders and Images from Google Cloud Storage with Laravel使用 Laravel 从 Google Cloud Storage 获取所有文件夹和图像
【发布时间】:2017-09-28 09:08:35
【问题描述】:

我正在使用laravel-google-cloud-storage 来存储图像并一张一张地检索它们。我是否可以从 Google Cloud Storage 中获取所有文件夹和图像?如果可能,我该如何完成?

我试图使用这个flysystem-google-cloud-storage 来检索它,但它们与我提供的第一个链接相似。

我想要实现的是我想使用谷歌云存储选择一个包含所有文件夹和图像的图像并将其放在我的表单中,而不是从我的本地选择图像。

更新:

这是我到目前为止从documentation 开始尝试的。

    $storageClient = new StorageClient([
        'projectId' => 'project-id',
        'keyFilePath' => 'myKeyFile.json',
    ]);
    $bucket = $storageClient->bucket('my-bucket');
    $buckets = $storageClient->buckets();

然后尝试添加foreach,它返回空,而且我的存储桶中有 6 个文件夹。

foreach ($buckets as $bucket) {
    dd($bucket->name());
}

【问题讨论】:

    标签: php laravel google-cloud-storage


    【解决方案1】:

    我的帖子已经一个星期没有得到回复了。我只是将上周以来我所做的事情发布并分享给任何人。

    我目前正在使用 Laravel 5.4。

    所以我在我的应用程序中安装了laravel-google-cloud-storageflysystem-google-cloud-storage

    我创建了一个不同的控制器,因为我通过 Ajax 从 Google Cloud Storage 检索图像。

    您需要做的就是获取您的 Google Cloud Storage 凭据,该凭据可以位于您的 Google Cloud Storage 控制面板中 > 查找 APIs,然后点击下面的链接,上面写着“转到 APIs 概述> 凭据。只需下载 JSON 文件格式的凭据并将其放在您的根目录或您想要的任何位置(我仍然不知道我应该将该文件正确放置在哪里)。然后我们获取您的 Google Cloud Storage 项目 ID,可位于仪表板中。

    然后这是我在控制器中的设置,它从我的 Laravel 应用程序连接到 Google Cloud Storage,我可以上传、检索、删除、复制文件。

    use Google\Cloud\Storage\StorageClient;
    use League\Flysystem\Filesystem;
    use League\Flysystem\Plugin\GetWithMetadata;
    use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;
    
    class GoogleStorageController extends Controller
    {
    
        // in my method
        $storageClient = new StorageClient([
            'projectId' => 'YOUR-PROJECT-ID',
            'keyFilePath' => '/path/of/your/keyfile.json',
        ]);
    
        // name of your bucket
        $bucket = $storageClient->bucket('your-bucket-name');
        $adapter = new GoogleStorageAdapter($storageClient, $bucket);
        $filesystem = new Filesystem($adapter);
    
        // this line here will retrieve all your folders and images
        $contents = $filesystem->listContents();
    
        // you can get the specific directory and the images inside 
        // by adding a parameter
        $contents = $filesystem->listContents('directory-name');
    
        return response()->json([
            'contents' => $contents
        ]);
    }
    

    【讨论】: