diff --git a/src/file.ts b/src/file.ts index 9372496bd..93d0538cc 100644 --- a/src/file.ts +++ b/src/file.ts @@ -3061,6 +3061,25 @@ class File extends ServiceObject { ); } + /** + * The public URL of this File + * Use {@link File#makePublic} to enable anonymous access via the returned URL. + * + * @returns {string} + * + * @example + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * const publicUrl = file.publicUrl(); + * // publicUrl will be "https://storage.googleapis.com/albums/my-file" + */ + publicUrl(): string { + return `${this.storage.apiEndpoint}/${this.bucket.name}/${this.name}`; + } + move( destination: string | Bucket | File, options?: MoveOptions diff --git a/test/file.ts b/test/file.ts index 6690a5998..f418f07e6 100644 --- a/test/file.ts +++ b/test/file.ts @@ -3455,6 +3455,48 @@ describe('File', () => { }); }); + describe('publicUrl', () => { + it('should return the public URL', done => { + const NAME = 'file-name'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${NAME}` + ); + done(); + }); + + it('with slash in the name', done => { + const NAME = 'parent/child'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${NAME}` + ); + done(); + }); + + it('with tilde in the name', done => { + const NAME = 'foo~bar'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${NAME}` + ); + done(); + }); + + it('with non ascii in the name', done => { + const NAME = '\u2603'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${NAME}` + ); + done(); + }); + }); + describe('isPublic', () => { const sandbox = sinon.createSandbox();