Home > Mobile >  How to get downloadUrl firebase storage with firebase admin sdk and put in img html's tag in no
How to get downloadUrl firebase storage with firebase admin sdk and put in img html's tag in no

Time:10-19

I am building the image upload system. I want to use the Firebase Admin sdk for handling this process. How to get the url to store in my Google Cloud Storage and fetch them on display in img tag (html) when the uploading is completed.

try {
    const file = req.file;
    const bucket = admin.storage().bucket();
    const imageBuffer = Buffer.from(file.buffer, "base64");
    const imageByteArray = new Uint8Array(imageBuffer);
    const options = {
      resumable: false,
      metadata: { contentType: file.mimetype },
      predefinedAcl: "publicRead",
      public: true,
    };
    const files = bucket.file(`img/${file.originalname}`);
    await files.save(imageByteArray, options);
    const field = await files.getMetadata();
    console.log(field);
  } catch (e) {
    console.error(e);
  }

CodePudding user response:

With the Node.js Admin SDK you should do as follows, using the getSignedUrl() method:

const { initializeApp, cert } = require('firebase-admin/app');
const { getStorage } = require('firebase-admin/storage');

const serviceAccount = require('./path/to/serviceAccountKey.json');

initializeApp({
  credential: cert(serviceAccount),
  storageBucket: '<BUCKET_NAME>.appspot.com'
});


// ...

async function getSignedURL(fileName) {
    const bucket = getStorage().bucket();
    // Or const bucket = admin.storage().bucket(); like you do in your question, depending on where and how you execute the code
    const file = bucket.file(fileName);

    const signedURLconfig = { action: 'read', expires: '01-01-2030' };
    // See more options of the config object in the SDK documentation (link above)

    const signedURLArray = await file.getSignedUrl(signedURLconfig);
    return signedURLArray[0];
}


// Use the above function to save the signed URL to Firestore
const fileName = "...";
getSignedURL(fileName)
.then(signedURL => {
    admin.firestore().collection("urls_collection")
    .add({url: signedURL, foo: "bar", bar: "foo"})
});
  • Related