how to send an image in a webSocket request using postman

Viewed 650

I am new to socket.io and want to send images using postman in a WebSocket request. I have searched for it but could not found any reasonable answer. I have attached the SS of my postman request.

Following is the server-side listener code for the socket.io

$socket->on('send-message', function ($data) use ($io, $socket) {

    $validator = Validator::make($data, [
        'token' => 'required',
        'socket_id' => 'required',
        'receiver_id' => 'required',
        'message' => 'required',
        'file' => 'required|file|image'
    ]);

    if ($validator->fails())
        return $io->emit('error', json_encode(['message' => $validator->messages()]));
                    
    return $io->emit('success', json_encode(['message' => 'image uploaded successfully']));

});

1 Answers

You could send the image as binary data frames:

WebSocket .send() method can send either text or binary data. "socket.send(body)" allows body in string or a binary format, including Blob, ArrayBuffer, etc. No settings required: just send it out in any format.

So basically:

WebSocket.send(000100101010000010011100.....)

BUT - a far simpler solution would be to use a Base64 string, as ALL browsers support it natively:

WebSocket.send('data:image/png;base64,iVBORw0KGgoAAAANSUhEU .......')
Related