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 ?
Firebase provides secure file uploads and downloads for Firebase application. This article explains how to build an Android application with the ability to select the image from the mobile gallery and upload images to Firebase Storage.
The Admin SDK is a set of server libraries that lets you interact with Firebase from privileged environments to perform actions like: Read and write Realtime Database data with full admin privileges.
Follow these steps to upload an image to Firebase storage: Import the default Firebase app module. Create an instance of the Firebase storage API and use the ref function to get a reference instance to upload an image. Invoke the putFile function with a file path/URI to upload the file to Firebase storage.
Connect to Firebase gradle file, you can use the Tools menu and select Firebase. This will pop out the Firebase Assistant with a list of menu choices. Scroll down to Storage and add Firebase to your project. Choose an existing project or create a new one then add Firebase Storage dependency.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With