Hypothesis
Hypothesis

Reputation: 1389

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

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?

Upvotes: 0

Views: 448

Answers (1)

gog
gog

Reputation: 11347

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.

Upvotes: 3

Related Questions