1

I am sorry. I previously make the same question but it was considered duplicate to this answer . I really don't understand the answer there and I don't understand why that question will answer my problem. it seems very different to me. I need to get image object but the answer there is to create a stream. could someone please help me to relate the answer from there to my problem ? I am new in cloud function. please

=======================================================================

If I use Cloud Functions for Firebase Cloud Storage triggers. I can get the image object like this

exports.compressImage = functions.region("asia-east2").storage.object().onFinalize(async (object) => {
    
   // I can get the `object` easily in here

})

but now I want do something using firestore trigger, and I want to get an object from my bucket in my firestore trigger

exports.dbEventsOnCreate = functions..firestore.document(path).onCreate(async (snapshot,context) => {

    // I want to get an image `object` with a specific path from firebase storage bucket in here

})

and here is the path of my image in firebase storage

gs://xxx.appspot.com/eventPoster/{uid}/{imageID}

enter image description here

so how to get image object from bucket in the path like that inside my cloud function firestore trigger ?

sarah
  • 3,819
  • 4
  • 38
  • 80

1 Answers1

2

To handle the file on the cloud function you can follow this guide you will find more detailed info ut in a few words

To download a file:

// Download file from bucket.
const bucket = admin.storage().bucket(fileBucket);
const tempFilePath = path.join(os.tmpdir(), fileName);
const metadata = {
  contentType: contentType,
};
await bucket.file(filePath).download({destination: tempFilePath});
console.log('Image downloaded locally to', tempFilePath);

That will save the image to a temporary folder since this is what is recomended on the docs.

Use gcs.bucket.file(filePath).download to download a file to a temporary directory on your Cloud Functions instance. In this location, you can process the file as needed.

To upload the file:

await bucket.upload(tempFilePath, {
  destination: thumbFilePath,
  metadata: metadata,
});
// Once the thumbnail has been uploaded delete the local file to free up disk space.
return fs.unlinkSync(tempFilePath);
Louis C
  • 645
  • 5
  • 12
  • what is the `fileBucket `? if I read the documenation, it comes from `object.bucket` . gs://myApp.appspot.com ? – sarah Jul 01 '20 at 00:51
  • fileBucket is the constant declared on the example. They use it to store the bucket that stores the files. It can be called whatever you like. – Louis C Jul 10 '20 at 15:14