Socket.io聊天应用程序也可以发送图像甚至文件 [英] Socket.io chat app that can also send image and even file

查看:57
本文介绍了Socket.io聊天应用程序也可以发送图像甚至文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近对 Socket.io 项目很感兴趣,我想知道是否有一种无需使用其他库即可轻松发送图像甚至其他类型文件的方法.我并没有尝试将文件上传到服务器进行存储,我只是想将其广播给当时在聊天室中的那些人.因此,代码应该最少.但是我真的很擅长编码/解码,所以一些示例代码会很棒.

I've been interested in the Socket.io project recently and I wonder if there's easy way to send image or even other type of files without having to use other library. I'm not trying to upload the file to the server to store, I just want to broadcast it to those who are in the chat room at that moment. So the code should be minimal. However I'm really bad at encoding/decoding stuff, so some example code would be great.

推荐答案

我改编了Socket.io的官方聊天示例,并添加了通过base64编码发送文件/图像甚至视频的功能,您可以看看 client.js index.js 中的源代码是最相关的部分,希望对您有所帮助.

I've adapted the official chat example of Socket.io and added functionality of sending file/images and even videos through base64 encoding, you can have a look at the source code in client.js and index.js, below are the most relevant part, hope it's helpful to you.

在客户端:

$('#uploadfile').bind('change', function(e){
    var data = e.originalEvent.target.files[0];
    readThenSendFile(data);      
});

function readThenSendFile(data){

    var reader = new FileReader();
    reader.onload = function(evt){
        var msg ={};
        msg.username = username;
        msg.file = evt.target.result;
        msg.fileName = data.name;
        socket.emit('base64 file', msg);
    };
    reader.readAsDataURL(data);
}

在服务器端:

socket.on('base64 file', function (msg) {
    console.log('received base64 file from' + msg.username);
    socket.username = msg.username;
    // socket.broadcast.emit('base64 image', //exclude sender
    io.sockets.emit('base64 file',  //include sender

        {
          username: socket.username,
          file: msg.file,
          fileName: msg.fileName
        }

    );
});

这是项目:

https://github.com/Arch1tect/Chatbox

这篇关于Socket.io聊天应用程序也可以发送图像甚至文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆