Socket – Send image in chat with socket using Nodejs

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
        }

    );
});

 

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes4
No3
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.