I am using Firebase Storage to create and send image url's to Firebase Database. I have this working well when I have both a 'currentUser' and a Firebase Storage child reference hardcoded. But, how do I grab the actual currentUser from Firebase Database and put a fluid name to the child reference/references? I've seen some possible answers to this in Java. But not Javascript. Here's my code:
// openImage() is the function that grabs a photo from the camera roll
// I'm using react-native btw, so some of this code is handling the
// blob.
openImage() {
this.setState({ loading: true });
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
// if I use this code, it won't return the urls: const {currentUser}
// = firebase.auth()
// So, I've got the 'currentUser' hardcoded in as "12345"
const { currentUser } = "12345"
// ImagePicker.openPicker() is just a library to access the camera roll
ImagePicker.openPicker({
width: 400,
height: 300,
cropping: true,
mediaType: 'photo',
}).then(image => {
const imagePath = image.path;
let uploadBlob = null;
const storage = firebase.storage();
const storageRef = storage.ref(currentUser);
//I also have the .child reference name hardcoded as 'dp.jpg'
const imageRef = storageRef.child('dp.jpg');
const mime = 'image/jpg';
fs.readFile(imagePath, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` });
})
.then((blob) => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
return imageRef.getDownloadURL();
})
.then((url) => {
const { image } = this.props;
this.props.entryUpdate({ prop: 'image', value: url })
});
});
}
The image url is then passed to Firebase Database and sets it as a key of 'image' and a value of 'dp.jpg'. With the hardcoding, this works fine, but for only one image and one user (or folder in Firebase Storage) of course. I'm aware of how Firebase Realtime Database will assign it's own id number to an item as in:
const { currentUser } = firebase.auth();
const item = firebase.database().ref(`/users/${currentUser.uid}/items`)
.push();
return () => {
item.set({ make, model, year, uid: item.key, image })
where item.key is generated by Firebase, thus it doesn't have to be hardcoded in. Is it possible to achieve this in Firebase Storage for both the image child name and the 'currentUser'? And do I really need to assign each image to a 'currentUser' folder in Firebase storage since the mobile app only is fetching the url from the database?
.once('value')
onto thestorage.ref(currentUser)
? Or Have you tried to log what it returns? Just assuming. According to documentation examples shouldn't you doconst item = firebase.storage().ref().child(currentUser)
? – parohy