React Native / Firebase - upload image with additional info - firebase

I used this block of code to select an image when button is pressed to upload to firebase.
<TouchableHighlight onPress={ () => this._pickImage() }
style={styles.button}>
<Text
style={styles.buttonText}>
Select a Photo
</Text>
</TouchableHighlight>
_pickImage() {
this.setState({ uploadURL: '' })
ImagePicker.launchImageLibrary({}, response => {
uploadImage(response.uri)
.then(url => this.setState({ uploadURL: url }))
.catch(error => console.log(error))
});
}// end _pickImage
const uploadImage = (uri, mime = 'application/octet-stream') => {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
const sessionId = new Date().getTime()
let uploadBlob = null
const imageRef = storage.ref('images').child(`${sessionId}`)
fs.readFile(uploadUri, '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) => {
resolve(url)
})
.catch((error) => {
reject(error)
})
})
}
This works fine. How can I change this to let the user select photo and then hit another button store additional info for the image like Description entered by the user into the same data structure in firebase?

Related

How to Upload Image form Phone to Firebase Storage?

I'm trying to upload a Picture form my Phone to Firebase using Expo.
I get a uri form the Picture but not sure how to convert it, that I can uploade it to Firebase?
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
if (!result.cancelled) {
console.log('device URL: w',result.uri);
this.setState({ image: result.uri });
this.uploadImage(result.uri).then(resp =>{
alert('success')
}).catch(err=>{
console.log(err)
})
}
};
When i Log result.uri I get:
file:///var/mobile/Containers/Data/Application/1E5612D6-ECDB-44F4-9839-3717146FBD3E/Library/Caches/ExponentExperienceData/%2540anonymous%252FexpoApp-87f4a5f5-b117-462a-b147-cab242b0a916/ImagePicker/45FA4A7B-C174-4BC9-B35A-A640049C2CCB.jpg
How can I convert it to a format that works for firebase?
you can convert the image to a base64, there are several libraries that can do that.
You need to convert the image to a base64, here is an example using rn-fetch-blob
https://github.com/joltup/rn-fetch-blob
export const picture = (uri, mime = 'application/octet-stream') => {
//const mime = 'image/jpg';
const { currentUser } = firebase.auth();
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
return ((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
let uploadBlob = null;
const imageRef = firebase.storage().ref('your_ref').child('child_ref');
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` });
})
.then((blob) => {
uploadBlob = blob;
imageRef.put(blob._ref, blob, { contentType: mime });
})
.then(() => {
//take the downloadUrl in case you want to downlaod
imageRef.getDownloadURL().then(url => {
// do something
});
});
});
};

RNFetchBlob is not working to upload image

I am trying to make a upload function for my Firebase Cloud Storage. I am using RNFetchBlob, along with react-native-image-picker. I can select photos, but it will not upload. All other Firebase functions works great and it is installed through React-Native-Firebase...
Nothing seems to happen after 'fs.readFile'.
import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Platform,
Image,
ActivityIndicator
} from 'react-native'
import ImagePicker from 'react-native-image-picker'
import RNFetchBlob from 'rn-fetch-blob'
import firebase from 'react-native-firebase';
const storage = firebase.storage()
// Prepare Blob support
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
const uploadImage = (uri, mime = 'application/octet-stream') => {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
const sessionId = new Date().getTime()
let uploadBlob = null
const imageRef = storage.ref('images').child('${sessionId}')
fs.readFile(uploadUri, '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) => {
resolve(url)
})
.catch((error) => {
reject(error)
})
})
}
class Demo extends Component {
constructor(props) {
super(props)
this.state = {}
}
_pickImage() {
this.setState({ uploadURL: '' })
ImagePicker.launchImageLibrary({}, response => {
uploadImage(response.uri)
.then(url => this.setState({ uploadURL: url }))
.catch(error => console.log(error))
})
}
render() {
return (
<View style={ styles.container }>
{
(() => {
switch (this.state.uploadURL) {
case null:
return null
case '':
return <ActivityIndicator />
default:
return (
<View>
<Image
source={{ uri: this.state.uploadURL }}
style={ styles.image }
/>
<Text>{ this.state.uploadURL } {this.state.uploadURL}</Text>
</View>
)
}
})()
}
<TouchableOpacity onPress={ () => this._pickImage() }>
<Text style={ styles.upload }>
Upload
</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
image: {
height: 200,
resizeMode: 'contain',
},
upload: {
textAlign: 'center',
color: '#333333',
padding: 10,
marginBottom: 5,
borderWidth: 1,
borderColor: 'gray'
},
})
export default Demo
I get this error in my console when selecting a photo:
filePath.replace is not a function. (In 'filePath.replace('file://',
'')', 'filePath.replace' is undefined)]
Just pass the image url directly to storage ref. You don't need to create a blob file anymore. I guess firebase handles it internally now.
Here an example i just tested together with react-native-image-crop-picker:
import firebase from 'react-native-firebase';
import ImagePicker from 'react-native-image-crop-picker';
export default class ImageUploadService {
static init() {}
static openPickerAndUploadImage() {
const uid = '12345';
ImagePicker.openPicker({
width: 300,
height: 300,
cropping: true,
mediaType: 'photo',
})
.then(image => {
const imagePath = image.path;
const imageRef = firebase
.storage()
.ref(uid)
.child('dp.jpg');
let mime = 'image/jpg';
imageRef
.put(imagePath, { contentType: mime })
.then(() => {
return imageRef.getDownloadURL();
})
.then(url => {
// You could now update your users avatar for example
//firebase.database().ref('users').child(uid).update({ ...userData})
console.log('URL', url);
});
})
.catch(error => {
console.log(error);
});
}
}
ImageUploadService.init();
Now just call ImageUploadService.openopenPickerAndUploadImage() in one of your components.
I am sure this will also work with react-native-image-picker too, just remove the blob parts in your code and pass the image url directly to your imageRef.put
==>
const uploadImage = (uri, mime = 'application/octet-stream') => {
return new Promise((resolve, reject) => {
const imagePath = uri;
const imageRef = firebase
.storage()
.ref('images')
.child('dp.jpg');
let mime = 'image/jpg';
imageRef
.put(imagePath, { contentType: mime })
.then(() => {
return imageRef.getDownloadURL();
})
.then(resolve)
.catch(reject);
});
};

Add Firebase image URL to my collection

I have the following method I'm accessing when my VueJS component is loading:
getServices () {
fb.servicesCollection.get().then(querySnapshot => {
this.serviceList = []
querySnapshot.forEach(doc => {
const { name, icon } = doc.data()
fb.storage.ref().child(icon).getDownloadURL().then(function (url) {
console.log(url)
})
this.serviceList.push({id: doc.id, name: name, icon: 'iconURL'})
})
this.isLoading = false
}).catch(error => {
console.log(error)
})
}
What I want to achieve is to get the url to replace the current 'iconURL' string. Didn't find any method to do that in the last couple of hours. Please help!
The following should do the trick. (However note that I could no test it, so it may need a bit of fine tuning... You can report how it works in the comments and we correct it if necessary)
Since you want to execute several getDownloadURL() asynchronous calls to Firebase Storage in parallel, you have to use Promise.all(), since getDownloadURL() returns a promise, see the doc.
getServices () {
let namesArray = []
let docIdArray = []
fb.servicesCollection.get().then(querySnapshot => {
this.serviceList = []
let promises = []
querySnapshot.forEach(doc => {
const icon = doc.data().icon;
promises.push(fb.storage.ref().child(icon).getDownloadURL())
namesArray.push(doc.data().name)
docIdArray.push(doc.id)
})
return Promise.all(promises)
})
.then(results => {
results.forEach((value, index) => {
this.serviceList.push({id: docIdArray[index], name: namesArray[index], icon: value})
})
})
}).catch(error => {
console.log(error)
})
}
This is how I got it in the end...
getServices () {
fb.servicesCollection.get().then(querySnapshot => {
this.serviceList = []
querySnapshot.forEach(doc => {
const { name, icon } = doc.data()
fb.storage.ref(icon).getDownloadURL().then(url => {
this.serviceList.push({id: doc.id, name: name, icon: url})
})
})
this.isLoading = false
}).catch(error => {
console.log(error)
})
}
Thank you for all your efforts to help me!!! Highly appreciate it!

TypeError: Cannot set property 'words' of undefined

I have this action in my vuex store:
loadExercises ({commit}) {
commit('setLoading', true)
const db = firebase.firestore()
db.collection('exercises').get()
.then(querySnapshot => {
const exercises = []
querySnapshot.forEach((doc) => {
exercises.push({
title: doc.data().title,
language: doc.data().language,
translated: doc.data().translated,
lastOpen: doc.data().lastOpen,
dueDate: doc.data().dueDate,
uid: doc.data().uid,
userId: doc.data().userId,
words: [{ word: '', uid: '', translation: '' }]
})
db.collection('exercises').doc(doc.data().uid).collection('words').get()
.then(words => {
const wordsArray = []
words.forEach(word => {
wordsArray.push(word.data())
})
let exercise = this.getters.loadedExercise(doc.data().uid)
exercise.words = wordsArray
})
.catch(error => {
commit('setLoading', false)
console.log(error)
})
})
commit('setLoading', false)
commit('setLoadedExercises', exercises)
})
.catch(error => {
commit('setLoading', false)
console.log(error)
})
}
It is supposed to fetch exercises from a firebase cloudstore db. It works on some routes but not all.
When using these two getters it works:
loadedExercises (state) {
return state.loadedExercises
},
loadedExercise (state) {
return (exerciseId) => {
return state.loadedExercises.find(exercise => {
return exercise.uid === exerciseId
})
}
}
But when I use these getters:
upcomingExercises (state, getters) {
return getters.loadedExercises.filter(exercise => {
return exercise.dueDate > 0
})
},
latestExercises (state, getters) {
return getters.loadedExercises.splice(0, 5)
},
it does not work I just get "TypeError: Cannot set property 'words' of undefined". What is it that I do wrong?
It looks to me like you aren't returning the values back to the function.
Try replacing
db.collection('exercises').get()
with
return db.collection('exercises').get()
and
db.collection('exercises').doc(doc.data().uid).collection('words').get()
with
return db.collection('exercises').doc(doc.data().uid).collection('words').get()

react-native-fetch-blob is blocking firebase calls n react native app

I have a react native app that uses Firebase, firestore.
for uploading images i am using "react-native-fetch-blob" to create a Blob.
in the js file that I use to upload the file, my code look like this:
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
**
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
**
because of this window.XMLHttpRequest my app is blocked and not getting any response from firebase(not catch / nothing => just passing thrue the code).
if i removed this line i can read/write to the firestore, bat I can't upload an image.
is there anything i can do for uploading images and keep writing to firestore?
Heare is my page:
import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase';
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
export const choozFile = (isSmalImg) => {
let options = {
width: isSmalImg ? 100 : 690,
height: isSmalImg ? 100 : 390,
cropping: true,
mediaType: 'photo'
};
return new Promise((resolve, reject) => {
ImagePicker.openPicker(options).then(response => {
let source = { uri: response.path };
resolve({ avatarSource: source, isProfileImg: isSmalImg })
})
});
}
export const addReportToFirebase = (obj = {}, uri, isProfile, mime = 'application/octet-stream') => {
obj["uId"] = "JtXNfy34BNRfCoRO6luwhIJke0l2";
const storage = firebase.storage();
const db = firebase.firestore();
const uploadUri = uri;
const sessionId = new Date().getTime();
let uploadBlob = null;
const imageRef = storage.ref(`images${isProfile ? '/profile' : ''}`).child(`${sessionId}`)
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
imageRef.getDownloadURL().then((url)=>{
obj['image'] = url;
db.collection("reports").add(obj).then(() => {
console.log("Document successfully written!");
}).catch((err) => {
console.error("Error writing document: ", err);
});
})
})
.catch((error) => {
console.log('upload Image error: ', error)
})
};
I had same issue , i did some trick to resolve this. This might not be most correct solution but it worked for me.
Trick is keep RNFetchBlob.polyfill.XMLHttpRequest in window.XMLHttpRequest only for the upload operation. Once you done with uploading image to storage revert window.XMLHttpRequest to original value.
your code will look like this.
import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase';
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.Blob = Blob
export const choozFile = (isSmalImg) => {
let options = {
width: isSmalImg ? 100 : 690,
height: isSmalImg ? 100 : 390,
cropping: true,
mediaType: 'photo'
};
return new Promise((resolve, reject) => {
ImagePicker.openPicker(options).then(response => {
let source = { uri: response.path };
resolve({ avatarSource: source, isProfileImg: isSmalImg })
})
});
}
export const addReportToFirebase = (obj = {}, uri, isProfile, mime = 'application/octet-stream') => {
obj["uId"] = "JtXNfy34BNRfCoRO6luwhIJke0l2";
const storage = firebase.storage();
const db = firebase.firestore();
const uploadUri = uri;
const sessionId = new Date().getTime();
let uploadBlob = null;
//keep reference to original value
const originalXMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
const imageRef = storage.ref(`images${isProfile ? '/profile' : ''}`).child(`${sessionId}`)
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close();
//revert value to original
window.XMLHttpRequest = originalXMLHttpRequest ;
imageRef.getDownloadURL().then((url)=>{
obj['image'] = url;
db.collection("reports").add(obj).then(() => {
console.log("Document successfully written!");
}).catch((err) => {
console.error("Error writing document: ", err);
});
})
})
.catch((error) => {
console.log('upload Image error: ', error)
})
};
that simple,,u can try this to upload image
<i>
getSelectedImages = (selectedImages, currentImage)=>{
const image = this.state.uri
let uploadBlob = null
let mime = 'image/jpg'
const originalXMLHttpRequest = window.XMLHttpRequest;
const originalBlob = window.Blob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = RNFetchBlob.polyfill.Blob
const imageRef = firebase.storage().ref('posts').child(this.state.uri)
RNFetchBlob.fs.readFile(image, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
window.XMLHttpRequest = originalXMLHttpRequest ;
window.Blob = originalBlob
return imageRef.getDownloadURL()
})
.then((url) => {
firebase.database().ref('groub').child(params.chat).child('message').push({
createdAt:firebase.database.ServerValue.TIMESTAMP,
image:url,
user:{
_id:params.id,
name:params.name,
},
})
alert('Upload Sukses')
})
.catch((error) => {
console.log(error);
})
}
</i>

Resources