Send Blob/Arraybuffer object by Websocket

Asked

Viewed 28 times

1

I am making a Websocket connection and trying to send a Blob/Arraybuffer object resulting from a screen save, but what arrives on the server instead of bytes is

[object ArrayBuffer]


Example of a code :

    var arrayBuffer;
    var fileReader = new FileReader();
    fileReader.onload = function(event) {
        arrayBuffer = event.target.result;
        socket.send("{\"data\":\"" + arrayBuffer + "\"}");
    };
    fileReader.readAsArrayBuffer(blob);

From now on I thank the collaborator.

1 answer

0

After a while in this problem I solved, and I come here to leave the answer in case someone finds this question later.
I solved with the following code

  socket.send("{\"data\":\"" + _arrayBufferToBase64(byteArray) + "\"}");

  function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
 }

I think it’s worth mentioning that I had problems with very large submissions, so I changed my approach from Websocket to Socket.io, but then I had to change my backend by not having lib socket.io for the language

Browser other questions tagged

You are not signed in. Login or sign up in order to post.