如何将文件上传到谷歌云存储并将其设置为公共权限并获取链接

时间:2016-08-09 23:09:17

标签: php google-cloud-storage google-cloud-platform

我正在将文件上传到Google云端存储,我想上传具有公共权限的文件,以及是否有可能将链接恢复为响应。

现在我只上传...

我的代码

require_once  dirname(dirname(__FILE__)).'/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('/blabla.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);
$storage = new Google_Service_Storage($client);
$fileTmpName="blabla.jpg";
$file_name = "bodzin";
$obj = new Google_Service_Storage_StorageObject();
$obj->setName($file_name);
$storage->objects->insert(
"creatives_new",
$obj,
['name' => $file_name, 'data' => file_get_contents($fileTmpName),'uploadType' => 'media']
);

1 个答案:

答案 0 :(得分:0)

我找到了这颗宝石:

https://cloud.google.com/storage/docs/access-control/making-data-public#storage-make-object-public-php

use Google\Cloud\Storage\StorageClient;

/**
* Make an object publically accessible.
*
* @param string $bucketName the name of your Cloud Storage bucket.
* @param string $objectName the name of your Cloud Storage object.
*
* @return void
*/
function make_public($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
    printf('gs://%s/%s is now public' . PHP_EOL, $bucketName, $objectName);
}

还有一点值得注意的是,该链接似乎永远是 https://storage.googleapis.com/ /