Adam McGurk
Adam McGurk

Reputation: 476

Get publicly accessible URL from Google Cloud after upload PHP

The problem is after I upload an object to my publicly accessible Google Cloud bucket, I want to use the created URL immediately for another service. However, I don't see a way to get the mediaUrl that I could then use. All of the properties on the following method that would give me that are private:

$bucket->upload(
    fopen($_FILES['file']['tmp_name'], 'r'),
    array('name' => $name)
);

I've already tried var_dump-ing the above method to see if any of the public properties would give me the created URL, but it doesn't even have any public properties.

Here's the code I'm using to upload the data:

$storage = new StorageClient([
    'keyFilePath' => 'keyfile_json.json'
]);
$bucket = $storage->bucket('bucket');

$name = 'some/name/path/'.$_POST['name'];

    $bucket->upload(
        fopen($_FILES['file']['tmp_name'], 'r'),
        array('name' => $name)
);

The file is uploading, I just can't get the URL of the actual resource that I can then go use in a different API call to a different service.

How can I get the URL of the resource after it is uploaded?

Upvotes: 1

Views: 6748

Answers (2)

Joss Baron
Joss Baron

Reputation: 1524

You have two ways to achieve this:

  1. Creating the URL for public objects using the following sintaxis: https://storage.googleapis.com/[BucketName]/[ObjectName]

Where:

[BucketName] = your bucket

[ObjectName]= name of your uploaded object

  1. If you are using AppEngine Standard Environment, there is a method in the API PHP App Engine API: getPublicUrl(string $gs_filename, boolean $use_https) : string

Where:

$gs_filename, string, The Google Cloud Storage filename, in the format: gs://bucket_name/object_name.

$use_https, boolean, If True then return a HTTPS URL. Note that the development server ignores this argument and returns only HTTP URLs.

Here the API documentation.

Upvotes: 4

John Hanley
John Hanley

Reputation: 81414

You need to build the public Link URL yourself for public objects.

The format is simple https://storage.cloud.google.com/BucketName/ObjectName.

Upvotes: 6

Related Questions