I tried to upload a file on root in my Google cloud Storage by doing this:

$bucketName = "bucket-name.appspot.com";
        $objectName = $client_id . '_' . rand(0, 200) . '_' . $type . '.pdf';
        $storage = new StorageClient();
        $bucket = $storage->bucket($bucketName);
        $object = $bucket->upload($datas, [
            'name' => $objectName
        ]);

This worked and i successfully upload a file($datas).


Now i created a folder in my root storage and called it "contracts". So my $bucketName is updated to include the folder like this:

$bucketName = "bucket-name.appspot.com/contracts";
        $objectName = $client_id . '_' . rand(0, 200) . '_' . $type . '.pdf';
        $storage = new StorageClient();
        $bucket = $storage->bucket($bucketName);
        $object = $bucket->upload($datas, [
            'name' => $objectName
        ]);

As you can see this is now updated to: $bucketName = "bucket-name.appspot.com/contracts";. But this gives me this error now:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalid",
    "message": "Invalid bucket name: 'bucket-name.appspot.com/contracts'"
   }
  ],
  "code": 400,
  "message": "Invalid bucket name: 'bucket-name.appspot.com/contracts'"
 }
}

Why is that?

2 Answers

3
Community On Best Solutions

See:

You should add /contracts/ to $objectName.

$bucketName = "bucket-name.appspot.com";
$objectName = '/contracts/' . $client_id . '_' . rand(0, 200) . '_' . $type . '.pdf';
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($datas, [
    'name' => $objectName
]);
2
Kolban On

Withing Google Cloud Storage, there are only buckets and objects. The notion of folders is only an illusion. For example, a file that you wish to access as gs://yourbucket/yourfolder/yourfile is bucket yourbucket and file (object) yourfolder/yourfile.

There is a dedicated article on this story at How Subdirectories work.