Home > Blockchain >  How can I send photos and so on through my channel with my other peer?
How can I send photos and so on through my channel with my other peer?

Time:12-03

I have the channel already established with my other partner but at the moment I can only send messages. How could I send any file through it? i tried with formData() and FileReader() but i don't know how to read that long string on the other side.

connection.ondatachannel = (event) => {

channel = event.channel;


channel.onmessage = (event) => {

// I receive the messages
document.querySelector(".messages-content").innerHTML  = event.data   "<br>";

}


};

How could I read the string that is returned to me by the file reader when it is delivered?

CodePudding user response:

To send a file using a data channel, you can use the FileReader API to read the file and convert it into a string or ArrayBuffer. Once you have the file content as a string or ArrayBuffer, you can send it over the data channel using the send() method. Here is an example of how you could do this:

// Read the file using the FileReader API
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);

// When the file has been read, send it over the data channel
fileReader.onload = () => {
  channel.send(fileReader.result);
};

On the receiving end, you can use the onmessage event handler to receive the file content as a string or ArrayBuffer. You can then use the FileReader API again to convert the received data back into a file that can be used or saved. Here is an example of how you could do this:

channel.onmessage = (event) => {
  // Convert the received data back into a file using the FileReader API
  const fileReader = new FileReader();
  fileReader.readAsArrayBuffer(event.data);

  // When the file has been read, you can use it or save it
  fileReader.onload = () => {
    const file = new File([fileReader.result], "received-file.txt");
    // Use or save the file here...
  };
};

Note that the FileReader API is asynchronous, so you will need to use the onload event handler to ensure that the file has been fully read before you try to use or save it.

  • Related