How to stringy a javascript object with a blob as data in it?

Viewed 35

I am recording my webcam with MediaRecoder and sending each blob back to sever using Websocket as such :

 recorder = new MediaRecorder(canvasStream);
            recorder.ondataavailable = e => {
                ws.send(e.data)
            }

which works fine, however I want to have more control over the type of message or data that will be send through Websocket and therefore I went with the classic

ws.send(JSON.stringify({ type: 'REC', data: e.data }))

to no avail. I cannot obviously Parse the data back on the server. How can I send a blob to the server while stringifying my message?

1 Answers

Json is a text-based format, it cannot directly include binary data like Blobs. What you can do is to obtain the Blob's arrayBuffer, encode it with base64 or hex and send it as text. This will make the upload 1.5-2 times larger though.

Alternatively, you can try a binary transport, like MessagePack instead of json.

Related