Build a Socket.io Image Gallery or Multiple Files Upload CRUD App in Node.js & Express in Browser Using socketio-file-upload Library Full Project For Beginners

 

 

 

In this blog post we will be building a socket.io image gallery or file upload app in node.js and express using socketio-file-upload Library in javascript. All the full source code of the application will be given below.

 

 

 

# Get Started

 

 

 

In order to get started you need to make a package.json file by executing the below command

 

 

npm init -y

 

 

npm i express socket.io socketio-file-upload

 

 

npm i -g nodemon

 

 

After installing all these libraries make an index.js file and copy paste the following code

 

 

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)
app.use(express.static(__dirname + '/uploads'))


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

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

 

 

As you can see we have the basic express app and we have imported the socket.io library and now we have to import the socketio-file-upload library in the next step

 

 

// Require the libraries:
var SocketIOFileUpload = require("socketio-file-upload")
const fs = require('fs')

const express = require('express')
const app = express()
app.use(SocketIOFileUpload.router);

 

 

After importing it we need to make an index.html file in the root directory and copy paste the below html code

 

 

index.html

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Upload Files</title>
    <script src="/siofu/client.js"></script>
    <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <p>
      <label>Choose File: <input type="file" id="upload_input" /></label>
    </p>
    <div id="images"></div>
  </body>
</html>

 

 

nodemon index.js

 

 

Now if you open the browser  at the url localhost:8000 you will see the below screenshot

 

 

Now we need to write the javascript code to hande the file input element such that when the user selects the file then automatically file is uploaded to the server

 

 

First I will show the server side code in node.js so go to index.js file and copy paste the below code

 

 

io.sockets.on("connection", function (socket) {
  // Make an instance of SocketIOFileUpload and listen on this socket:
  var uploader = new SocketIOFileUpload();
  uploader.dir = "uploads";
  uploader.listen(socket);

  // Do something when a file is saved:
  uploader.on("saved", function (event) {
      event.file.clientDetail.name = event.file.name; 
  });

  // Error handler:
  uploader.on("error", function (event) {
    console.log("Error from uploader", event);
  });
});

 

 

Now I will show the client side javascript code go to index.html file and copy paste the below code

 

 

index.html

 

 

<script type="text/javascript">
      document.addEventListener(
        "DOMContentLoaded",
        function () {
          // Initialize instances:
          var socket = io.connect("");

          var siofu = new SocketIOFileUpload(socket);

          siofu.listenOnInput(document.getElementById("upload_input"));

          // Do something on upload progress:
          siofu.addEventListener("progress", function (event) {
            var percent = (event.bytesLoaded / event.file.size) * 100;
            console.log("File is", percent.toFixed(2), "percent loaded");
          });

          // Do something when a file is uploaded:
          siofu.addEventListener("complete", function (event) {
            console.log(event.detail.name);
            var img = document.createElement("img");
            img.setAttribute("style", "float:left;width:500px;height:300px");
            img.src = event.detail.name;
            img.addEventListener("click", (e) => {
              $.ajax({
                  method:'GET',
                  url:'/deleteimage',
                  data:{
                      path:event.detail.name
                  },
                  success:function(data){

                  }
              })
            });
            var div = document.getElementById("images");
            div.appendChild(img);
          });
        },
        false
      );
    </script>

 

 

FULL SOURCE CODE

 

 

index.html

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Upload Files</title>
    <script src="/siofu/client.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script type="text/javascript">
      document.addEventListener(
        "DOMContentLoaded",
        function () {
          // Initialize instances:
          var socket = io.connect("");

          var siofu = new SocketIOFileUpload(socket);

          siofu.listenOnInput(document.getElementById("upload_input"));

          // Do something on upload progress:
          siofu.addEventListener("progress", function (event) {
            var percent = (event.bytesLoaded / event.file.size) * 100;
            console.log("File is", percent.toFixed(2), "percent loaded");
          });

          // Do something when a file is uploaded:
          siofu.addEventListener("complete", function (event) {
            console.log(event.detail.name);
            var img = document.createElement("img");
            img.setAttribute("style", "float:left;width:500px;height:300px");
            img.src = event.detail.name;
            img.addEventListener("click", (e) => {
              $.ajax({
                  method:'GET',
                  url:'/deleteimage',
                  data:{
                      path:event.detail.name
                  },
                  success:function(data){

                  }
              })
            });
            var div = document.getElementById("images");
            div.appendChild(img);
          });
        },
        false
      );
    </script>
  </head>
  <body>
    <p>
      <label>Choose File: <input type="file" id="upload_input" multiple accept="image/*" /></label>
    </p>
    <div id="images"></div>
  </body>
</html>

 

 

index.js

 

 

// Require the libraries:
var SocketIOFileUpload = require("socketio-file-upload")
const fs = require('fs')

const express = require('express')
const app = express()
app.use(SocketIOFileUpload.router);
const http = require('http')
const { Server } = require('socket.io')
const server = http.createServer(app)
const io = new Server(server)
app.use(express.static(__dirname + '/uploads'))


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

app.get('/deleteimage', (req, res) => {
    console.log(req.query);
    res.json(req.query.path);
    fs.unlinkSync(__dirname + "/uploads/" + req.query.path, () => {
        
    })
})

io.sockets.on("connection", function (socket) {
  // Make an instance of SocketIOFileUpload and listen on this socket:
  var uploader = new SocketIOFileUpload();
  uploader.dir = "uploads";
  uploader.listen(socket);

  // Do something when a file is saved:
  uploader.on("saved", function (event) {
      event.file.clientDetail.name = event.file.name; 
  });

  // Error handler:
  uploader.on("error", function (event) {
    console.log("Error from uploader", event);
  });
});

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

 

 

 

 

DOWNLOAD FULL SOURCE CODE

 

Leave a Reply