Node.js Express Tutorial to Upload & Broadcast Base64 or Binary Image to all Sockets Using Socket.io in Browser Using Javascript Full Project For Beginners

 

 

npm init -y

 

 

npm i express socket.io nodemon

 

 

 

index.js

 

 

const express = require('express')

const app = express()

const http = require('http')

const {Server} = require('socket.io')

const server = http.createServer(app)

const io = new Server(server)

const PORT = process.env.PORT || 3000

let base64image = ""

app.get('/',(req,res) => {
    res.sendFile(__dirname + "/index.html")
})

io.on('connection',(socket) => {
    console.log("a user connected")

    socket.on('image',(data) => {
        console.log(data)
        base64image = data
        io.sockets.emit('image',data)
    })

    socket.emit('oldimage',base64image)


    socket.on('disconnect',() => {
        console.log('user disconnected')
    })
})

server.listen(PORT,() => {
    console.log("Server is listening on port 3000")
})

 

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <h1 class="text-center">
            Broadcast Base64 Images Using Socket.io
        </h1>
        <div class="form-group">
            <label for="image">Choose Image:</label>
            <input type="file" accept="image/*" id="file" class="form-control">
        </div>
        <img id="img" alt="">
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="socket.io/socket.io.js"></script>
<script>
    let socket = io("")

    document.getElementById('file').addEventListener('change', function () {
 
        const reader = new FileReader();
        reader.onload = function () {
            const base64 = this.result.replace(/.*base64,/, '');
            console.log(base64)
            let base64string = "data:image/jpeg;charset=utf-8;base64," + base64
            socket.emit('image', base64string);
        };
        reader.readAsDataURL(this.files[0]);

    }, false);

    socket.on('oldimage',(data) => {
        console.log(data)
        document.getElementById('img').src=data
    })

    socket.on('image',(data) => {
        console.log(data)
        document.getElementById('img').src = data
    })

</script>

</html>

 

 

 

Leave a Reply