taroimo
taroimo

Reputation: 1

I want to save the image from the cloud function to the firestore and get the URL

I would like to implement the following process on cloud functions (TypeScript).

  1. Get the image by URL
  2. Save image to Cloud Storage
  3. Get URL of the image saved in the firestore

I am trying to move it with the following code, there is 2 problem.

Code:

const bucket = admin.storage().bucket();
const url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';

request(
  { method: 'GET', url: url, encoding: null },
  async function (error, response, body) {
    if (!error && response.statusCode === 200) {
      const file = bucket.file('test/test.png');

      const metadata = {
        contentType: 'image/png'
      };
      try {
        await file.save(body, metadata);
      } catch (err) {
        console.log(err);
      }
    }
  }
);

It would be greatly appreciated if you could explain the details.

Upvotes: 0

Views: 977

Answers (1)

combuskenisthebest
combuskenisthebest

Reputation: 11

You should probably understand that when the URL is set to the saved image it defaults to a different one that Firebase issues it. You should probably look at this documentation to see how to get that URL: https://firebase.google.com/docs/storage/web/download-files. A way you could get the link (that you issued for it) onto the file, you should add it to the metadata like this:

const bucket = admin.storage().bucket();
const url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';

request(
  { method: 'GET', url: url, encoding: null },
  async function (error, response, body) {
    if (!error && response.statusCode === 200) {
      const file = bucket.file('test/test.png');

      const metadata = {
        contentType: 'image/png',
        url // <- add url here
      };
      try {
        await file.save(body, metadata);
      } catch (err) {
        console.log(err);
      }
    }
  }
);

Also the reason it may be taking so long is because getting the image and then adding the image to Firebase.

Upvotes: 1

Related Questions