I tried uploading the image to firebase and now I can't get the image URL
I uploaded the image successfully and can't get the image's URL link
const firebaseAdmin = require('firebase-admin');
const { v4: uuidv4 } = require('uuid');
// change the path of json file
const serviceAccount = require('./nodejs-be-upload-image-firebase-adminsdk-vzkga-bd1696a09f.json');
const admin = firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
});
const storageRef = admin.storage().bucket('gs://nodejs-be-upload-image.appspot.com');
async function uploadFile(path, filename) {
// Upload the File
const storage = await storageRef.upload(path, {
public: true,
destination: `/uploads/${filename}`,
metadata: {
firebaseStorageDownloadTokens: uuidv4(),
cacheControl: 'public, max-age=315360000',
contentType: 'image/jpeg',
},
});
//I want to get the URL of the image here
return storage[0];
// return storage[0].metadata.mediaLink;
}
module.exports = { uploadFile };
The Firebase Admin SDK wraps the Google Cloud Storage SDK, so their APIs are the same. The Cloud Storage SDK doesn't offer download URLs that are exactly like the ones provided by the mobile and web SDKs.
By setting the image or file as public (public: true) you wont be able to set a custom firebaseStorageDownloadTokens metadata.
There are some ways that you can get the public URL of an uploaded file.
Using getSignedUrl:
const admin = firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert({
// serviceAccount
}),
});
const gs = 'gs://'
const bucketName = '<project-id>.appspot.com';
const storageRef = admin.storage().bucket(`${gs}${bucketName}`);
async function uploadFile(path, filename) {
// Upload the File
const destination = `uploads/${filename}`;
const storage = await storageRef.upload(path, {
public: true,
destination: destination,
})
.then(() => {
const file = storageRef.file(destination);
return file.getSignedUrl({
action: 'read',
expires: '03-25-2023'
}).then(signedUrls => {
// signedUrls[0] contains the file's public URL
console.log(signedUrls[0]);
});
});
}
Using the Cloud Storage link:
async function uploadFile(path, filename) {
// Upload the File
const destination = `uploads/${filename}`;
const storage = await storageRef.upload(path, {
public: true,
destination: destination,
})
.then(() => {
console.log(`https://storage.googleapis.com/${bucketName}/${destination}`);
});
}
If you really do want to use customMetadata that has the firebaseStorageDownloadTokens then I would suggest to use the Web SDKs instead. Here's the documentation to start: