Socket.io chat application that can also send an image and even a file

Recently, I was interested in the Socket.io project, and I am wondering if there is an easy way to send an image or even other types of files without having to use another library. I am not trying to upload the file to the server for storage, I just want to transfer it to those who are in the chat at that moment. Therefore, the code should be minimal. However, I am really poor at coding / decoding, so some sample code will be great.

+6
source share
1 answer

I adapted the official Socket.io chat example and added the functionality of sending files / images and even video via base64 encoding, you can see the source code in client.js and index.js , the most important part below, I hope that it will be useful for you.

On the 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 the 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

+5
source

All Articles