7

I am trying to store images to firebase storage, I am using node.js.

import * as admin from 'firebase-admin';

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://xxx-app.firebaseio.com',
    storageBucket: 'xxxx-app.appspot.com'
});


function storeHeadShots(){

    const bucket = admin.storage().bucket();

    bucket.upload('./headshots/Acker.W.png', function(err, file){
        if (!err){
            console.log('file uploaded')
        } else {
            console.log('error uploading image: ', err)
        }
    });

}
storeHeadShots();

Now the above works fine, but I have a folder in storage users/ and inside this folder I am storing images. How do I access this folder ?

Yasir
  • 1,391
  • 2
  • 23
  • 44
  • Are you looking for a way to download the files? If so you can use [`file.download()`](https://github.com/firebase/firebase-admin-node/blob/master/test/integration/storage.spec.ts#L55) method. – Hiranya Jayathilaka Feb 01 '18 at 18:10
  • no man, I am looking for a way to reference the folder `users/` and inside that folder where the images reside... when doing this `const bucket = admin.storage().bucket()` it works fine but stores files/images in root level, I want to go one level deep , hence inside `users/` folder – Yasir Feb 03 '18 at 03:56

1 Answers1

12

For anybody who was trying to solve the same problem.

The example is taken from the official documentation here but it doesn't say anything about how to put a file inside a folder. The default example puts the file under the root of the bucket with the same name as the local file.

I had to dig a little deeper into the Cloud Storage class documentation here and I found that for the options a destination parameter exists that describes the file inside the bucket.

In the following example the local file images/bar.png will be uploaded to the default bucket's file /foo/sub/bar.png.

const bucket = admin.storage().bucket();

bucket.upload('images/bar.png', {
  destination: 'foo/sub/bar.png',

  gzip: true,
  metadata: {
    cacheControl: 'public, max-age=31536000'
  }
}).then(() => {
  console.log('file uploaded.');
}).catch(err => {
  console.error('ERROR:', err);
});

Hopefully that saved some time for others. Happy uploading!

Ewald Benes
  • 622
  • 6
  • 13