将 Access-Control-Allow-Origin header 添加到使用 PHP 客户端库上传的文件

Adding Access-Control-Allow-Origin header to file uploaded using PHP client library

我正在使用 Google 云平台 PHP 客户端库 (https://github.com/google/google-api-php-client) 将文件上传到我项目中的存储桶。我需要能够使用来自另一个域的 AJAX 请求来获取文件,因此需要添加 header

Access-Control-Allow-Origin: *

我绞尽脑汁想弄明白这个问题 - 我的 Google 搜索没有结果。参考代码示例:

$client = new Google_Client();  
$client->setApplicationName("Test");
$client->useApplicationDefaultCredentials();

$client->addScope('https://www.googleapis.com/auth/cloud-platform');

$storage = new Google_Service_Storage($client);
$file_name = "test.txt";
$file_content = "this is a test";

$postbody = array( 
    'name' => $file_name, 
    'data' => $file_content,
    'uploadType' => "media",
    'predefinedAcl' => 'publicRead'
    );

$gsso = new Google_Service_Storage_StorageObject();
$gsso->setName( $file_name );

$result = $storage->objects->insert( "my_bucket", $gsso, $postbody );

文件已正确上传,可以在存储桶中查看,但没有正确的 headers,因为我不知道如何添加它们。事实上,我什至找不到使用云平台控制台手动添加这些 header 的方法。感谢任何指点,谢谢

所以我终于找到了我需要的文档,只能为存储桶本身设置 CORS 配置(它不能在文件级别配置)。使用 gsutil 或 XML API 执行此操作的说明是 here

我创建了一个包含以下内容的 cors-json-file.json:

[
    {
      "origin": ["*"],
      "method": ["*"]
    }
]

然后运行

gsutil cors set cors-json-file.json gs://my_bucket

可以使用

查看存储桶的现有 CORS 配置
gsutil cors get gs://my_bucket

可以在 Google Bucket API Reference

中找到配置选项的完整列表

我不确定这是否是缓存问题,但这似乎仅适用于添加到存储桶的文件您更改 CORS 配置之后,但是我很高兴得到纠正

您还可以通过 PHP 使用 StorageClient in google-cloud-php 配置 CORS。

$storage = new StorageClient([
    'projectId' => '<project-id>',
    'keyFilePath' => '<path-to-key-file>',
]);

$cors = [
    [
        'maxAgeSeconds' => '3600',
        'method' => ['*'],
        'origin' => ['*'],
        'responseHeader' => ['Content-Type'],
    ],
]

// Creating a bucket with CORS
$storage->createBucket('<bucket-name>', [
    'location' => 'EU',
    'cors' => $cors,
]);

// Updating a bucket
$storage->bucket('<bucket-name>')->update([
    'cors' => $cors,
]);