Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble uploading media (images) to twilio programmable chat in react-native

I'm implementing programmable-chat in react-native using the npm package. Unfortunately, I'm stuck on being able to correctly upload messages with images to twilio. The twilio js documentation outlines 3 ways to create a Media Message. Sending: 1) FormData (doesn't seem applicable to me in react-native?), 2) a String, or 3) a Buffer.

I've tried many variations at this point and am stumped. I've been all over the place with both react-native-fs and react-native-fetch-blob and haven't cracked it yet.

Everything I try results in failure or in a String being uploaded. When the String is uploaded, I can complete a round trip by fetching the created Media Message, getting the the temporary url of the media attachment, manually fetching the String stored at that url, and then crafting a base64 data uri for the Image element with the fetched String. But I'm 99% sure that is 'doing it wrong'. If I do it right, Twilio should be storing an actual image for me and giving me a temporary url that I can directly feed to my Image element, right?

To sum up: I can get a base64 encoded string to be stored in twilio, but for the life of me I can't figure out how to get the image binary up there so as to be directly accessible when hitting the url it is at.

I feel like I've got to be missing something simple, but I'm out of ideas at the moment. Is there a way to get a Buffer set up in react native? Should I be trying something with FormData?

like image 604
Scott Roth Avatar asked Jan 01 '26 09:01

Scott Roth


1 Answers

I finally figured this out. This was just a problem not knowing how to get the file into a buffer in react native. I was finally able to get this working with a combination of react-native-fs and buffer. The code looks something like:

import RNFS from 'react-native-fs'

myMethod(twilioChannelObject, filePathString) {
  RNFS.readFile(filePath, 'base64').then((data) => {
    var Buffer = require('buffer/').Buffer
    data = Buffer.from(data, 'base64')

    twilioChannelObject.sendMessage({
      contentType: 'image/png',
      media: data
    }).then(id => {})
  })
}

This probably isn't the best practice way to solve the problem, but it got it to work for me, so moving on for now.

like image 76
Scott Roth Avatar answered Jan 04 '26 18:01

Scott Roth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!