【问题标题】:how to send an image in a webSocket request using postman如何使用邮递员在 webSocket 请求中发送图像
【发布时间】:2021-10-15 19:41:18
【问题描述】:

我是 socket.io 的新手,想在 WebSocket 请求中使用邮递员发送图像。我已经搜索过,但找不到任何合理的答案。我已附上我的邮递员请求的 SS。

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

});

【问题讨论】:

  • 我可能错了,但这不可能。事实上,socket.io 只是提供了一种通过套接字发送字节的方法,但没有提供任何解释这些字节的方法。也就是说,您有一些选择:对文件使用 base64 并对其进行解码,对其进行序列化,以便您可以直接在服务器中读取字节。您将无法按原样使用您的服务器代码。
  • 你不应该使用 WebSockets 发送大量数据
  • 根据上面的 cmets,您可以将图像(二进制)编码为 base-64 字符串并分段(块)发送,you shouldn't send large amount of that via WebSockets 除外。您可以只发送之前上传的媒体的 URL。
  • @Mujeeb 你的邮递员请求的 SS 在哪里......?

标签: javascript websocket socket.io postman


【解决方案1】:

可以将图片发送为binary data frames

WebSocket .send() 方法可以发送文本或二进制数据。 “socket.send(body)”允许body为字符串或二进制格式,包括Blob、ArrayBuffer等。无需设置:任意格式发送即可。

所以基本上:

WebSocket.send(000100101010000010011100.....)

但是 - 一个更简单的解决方案是使用 Base64 字符串,作为所有浏览器 support it natively:

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

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 2019-07-31
    • 1970-01-01
    • 2018-10-16
    • 2021-04-29
    • 2016-12-22
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多