使用Google Cloud Storage PHP API设置CORS配置不起作用

时间:2019-03-26 04:42:55

标签: php laravel cors google-cloud-storage

我正在使用PHP API设置Google Cloud Storage存储桶CORS配置,但似乎不起作用

我阅读了https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.96.0/storage/bucket

中提供的文档

这是我的Laravel源代码:

    use Google\Cloud\Core\ServiceBuilder;

    ...

    $projectId = 'myProjectId';
    $bucketName = 'myBucketName';

    $gcloud = new ServiceBuilder([
        'keyFilePath' => 'resources/google-credentials.json',
        'projectId' => $projectId
    ]);

    $storage = $gcloud->storage();
    $bucket = $storage->bucket($bucketName);

    //change bucket configuration
    $result = $bucket->update([
        'cors' => [
            'maxAgeSeconds' => 3600,
            'method' => [
                "GET","HEAD"
            ],
            "origin" => [
                "*"
            ],
            "responseHeader" => [
                "Content-Type"
            ]
        ]
    ]);

    //print nothing and bucket doesn't changed
    dd($bucket->info()['cors']);

执行此代码后,存储区CORS配置未更改 (我的老板不希望我使用gsutil shell命令来处理此问题)

2 个答案:

答案 0 :(得分:0)

我唯一需要更改的是在laravel中配置磁盘时,在为Google添加磁盘时在 config / filesystems.php 中使用以下代码:

'google' => [
    'driver' => 's3',
     'key' => 'xxx',
     'secret' => 'xxx',
     'bucket' => 'qrnotesfiles',
     'base_url'=>'https://storage.googleapis.com'
]

这是从请求中获取文件内容的代码示例:

$file = $request->file('avatar')

第二次将其保存到存储中:

Storage::disk('google')->put('avatars/' , $file);

答案 1 :(得分:0)

您非常亲密! CORS接受列表,因此您只需要进行一些修改:

$result = $bucket->update([
    'cors' => [
        [
            'maxAgeSeconds' => 3600,
            'method' => [
                "GET","HEAD"
            ],
            "origin" => [
                "*"
            ],
            "responseHeader" => [
                "Content-Type"
            ]
        ]   
    ]
]);

让我知道是否有帮助:)。