1

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']));

});
homer
  • 882
  • 8
  • 23
  • I may be wrong but that should not be possible. In fact socket.io just provides a way to send bytes through a socket but does not offer any way to interpret those. That said you have some alternatives: use base64 for your file and decode it, serialize it so you can read bytes directly in your server. You won't be able to use your server code as is. – homer Nov 11 '21 at 14:14
  • you shouldn't send big amount of data with WebSockets – evgeni fotia Nov 11 '21 at 18:46
  • As per the comments above, you can encode your image (binary) to a base-64 string and send it by pieces (chunks), except [you shouldn't send large amount of that via WebSockets](https://stackoverflow.com/a/56925975/1019059). You could send just the URL of the previously uploaded media instead. – Richard Cotrina Nov 12 '21 at 21:33
  • @Mujeeb where is your SS of postman req....? – MD. RAKIB HASAN Nov 15 '21 at 09:15

1 Answers1

2

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 .......')
Shaya
  • 2,792
  • 3
  • 26
  • 35