Reputation: 141
I want to send images with messages using gifted chat , Here is my code:
// for send message
const onSend =(messageArray) => {
const msg = messageArray[0]
const mymsg = {
...msg,
sentBy:user.uid,
sentTo:uid,
createdAt:new Date()
}
setMessages(previousMessages => GiftedChat.append(previousMessages,mymsg))
const docid = uid > user.uid ? user.uid+ "-" + uid : uid+"-"+user.uid
firestore().collection('chatrooms')
.doc(docid)
.collection('messages')
.add({...mymsg,createdAt:firestore.FieldValue.serverTimestamp()})
}
from here am sending messages and store them to firebase and showing fetching them back from firebase.
// display code
<GiftedChat
messages={messages}
onSend={text => onSend(text)}
user={{
_id: user.uid,
}}
alwaysShowSend
placeholder='Message'
renderSend={renderSend}
renderBubble={(props)=>{
return <Bubble
{...props}
wrapperStyle={{
right: {
backgroundColor:"#efc100",
},
left:{
marginLeft: -40
}
}}
/>
}}
thanks in advance
Upvotes: 0
Views: 4521
Reputation: 4849
Let's split the problem into small subproblems.
const pickImageasync = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
let imgURI = null;
const hasStoragePermissionGranted = status === "granted";
if(!hasStoragePermissionGranted) return null;
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 4],
quality: 1,
});
if (!result.cancelled) {
imgURI = result.uri;
}
return imgURI;
};
const uploadImageToStorage= async (imgURI ) => {
const ref = `messages/${[FILE_REFERENCE_HERE]}`
const imgRef = firebase.storage().ref(ref);
const metadata = { contentType: "image/jpg" };
// Fetch image data as BLOB from device file manager
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", imgURI, true);
xhr.send(null);
});
// Put image Blob data to firebase servers
await imgRef.put(blob, metadata);
// We're done with the blob, close and release it
blob.close();
// Image permanent URL
const url = await imgRef.getDownloadURL();
return url
};
const localImgURI = "file://path_to_file" // Replace with real path of uploaded image
const imgPermanentURL = await uploadImageToStorage(localImgURI)
firestore().collection('chatrooms')
.doc(docid)
.collection('messages')
.doc(messageId).update({image:imgPermanentURL})
Upvotes: 3