soloway
soloway

Reputation: 121

Socket.io chat app that can also send image and even file

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.

Upvotes: 12

Views: 17078

Answers (1)

Arch1tect
Arch1tect

Reputation: 4281

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.

On client side:

$('#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);
}

On server side:

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
        }

    );
});

Here's the project:

https://github.com/Arch1tect/Chatbox

Upvotes: 13

Related Questions