vainu
vainu

Reputation: 141

Want to send images using gifted chat with messages, and store them to firebase and fetch them back , and show in the chat

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

Answers (1)

Fiston Emmanuel
Fiston Emmanuel

Reputation: 4849

Let's split the problem into small subproblems.

  1. Get image from media library

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;
};



  1. Upload an image to Firebase Storage
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
};



  1. Update message document with image permanent URI
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

Related Questions