Skip to content
This repository was archived by the owner on Mar 3, 2026. It is now read-only.

Commit 5ec256e

Browse files
authored
feat: public url of a file (#1324)
* feat: public url of a file * removed log statement * changed function to use apiEndpoint * updated comment to assign publicUrl variable
1 parent aadec92 commit 5ec256e

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

src/file.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3061,6 +3061,25 @@ class File extends ServiceObject<File> {
30613061
);
30623062
}
30633063

3064+
/**
3065+
* The public URL of this File
3066+
* Use {@link File#makePublic} to enable anonymous access via the returned URL.
3067+
*
3068+
* @returns {string}
3069+
*
3070+
* @example
3071+
* const {Storage} = require('@google-cloud/storage');
3072+
* const storage = new Storage();
3073+
* const bucket = storage.bucket('albums');
3074+
* const file = bucket.file('my-file');
3075+
*
3076+
* const publicUrl = file.publicUrl();
3077+
* // publicUrl will be "https://storage.googleapis.com/albums/my-file"
3078+
*/
3079+
publicUrl(): string {
3080+
return `${this.storage.apiEndpoint}/${this.bucket.name}/${this.name}`;
3081+
}
3082+
30643083
move(
30653084
destination: string | Bucket | File,
30663085
options?: MoveOptions

test/file.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3455,6 +3455,48 @@ describe('File', () => {
34553455
});
34563456
});
34573457

3458+
describe('publicUrl', () => {
3459+
it('should return the public URL', done => {
3460+
const NAME = 'file-name';
3461+
const file = new File(BUCKET, NAME);
3462+
assert.strictEqual(
3463+
file.publicUrl(),
3464+
`https://storage.googleapis.com/bucket-name/${NAME}`
3465+
);
3466+
done();
3467+
});
3468+
3469+
it('with slash in the name', done => {
3470+
const NAME = 'parent/child';
3471+
const file = new File(BUCKET, NAME);
3472+
assert.strictEqual(
3473+
file.publicUrl(),
3474+
`https://storage.googleapis.com/bucket-name/${NAME}`
3475+
);
3476+
done();
3477+
});
3478+
3479+
it('with tilde in the name', done => {
3480+
const NAME = 'foo~bar';
3481+
const file = new File(BUCKET, NAME);
3482+
assert.strictEqual(
3483+
file.publicUrl(),
3484+
`https://storage.googleapis.com/bucket-name/${NAME}`
3485+
);
3486+
done();
3487+
});
3488+
3489+
it('with non ascii in the name', done => {
3490+
const NAME = '\u2603';
3491+
const file = new File(BUCKET, NAME);
3492+
assert.strictEqual(
3493+
file.publicUrl(),
3494+
`https://storage.googleapis.com/bucket-name/${NAME}`
3495+
);
3496+
done();
3497+
});
3498+
});
3499+
34583500
describe('isPublic', () => {
34593501
const sandbox = sinon.createSandbox();
34603502

0 commit comments

Comments
 (0)