Skip to content

Instantly share code, notes, and snippets.

@codebanesr
Last active June 3, 2020 20:21
Show Gist options
  • Save codebanesr/e4a4146352741d9e0ebbaefd1bcc09c7 to your computer and use it in GitHub Desktop.
Save codebanesr/e4a4146352741d9e0ebbaefd1bcc09c7 to your computer and use it in GitHub Desktop.

Sending images/Files/Binary Stream over websockets/socketio

Connect to the socket

this.socket = io(environment.socketUrl, {
  "transports": ["polling", "websocket"]
});

Start listening for the file upload event

this.socket.on("fileUpload", (data)=>{
  const { image, name } = data;
  console.log("some file was uploaded by the client");
  this.uploadedImages[name] = image;
})

Start listening for fileUpload events We listen for a fileUpload event and anytime that event is fired we send it over to the server. For simplicity sake, the data i will be sending is going to be a base64 encoded representation of the file. You will see that in a bit. Also we have a counter to tell user on the other side that a file upload has been started by someone else. The only catch here is that during file upload handle change method will be called multiple times. We dont want to send 3 different notifications. So to prevent that we only send notification, the first time handleChange event is called! Makes sense doesnot it?

counter = 0;
handleChange(files: FileList) {
    if (this.counter === 0) {
        this.counter++;
        this.socket.emit("info", `file upload has been started `);
    }
    const fileToUpload = files.item(0);
    const reader = new FileReader();
    reader.onload = (evt) => {
        this.socket.emit('fileUpload', { name: this.imageName, image: evt.target.result });
    };

    reader.onloadend = (data) => {
        this.counter = 0;
        this.msg.success(`file successfully uploaded`);
    }
    reader.readAsDataURL(fileToUpload);
}
Associated HTML code that does the trick
<input type="file" (change)="assignName(document); handleChange($event.target.files)" />
Backend code to handle image uploads

Organize your imports

const express = require('express');
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);

Start socket server

http.listen(8080, () => {
  console.log("listening on *:8080");
});

Attach all your events

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

  socket.on("message", (value) => {
    io.emit("message", value);
  });

  socket.on("fileUpload", (data)=>{
    console.log("fileYploaded started");
    io.emit("fileUpload", data);
  })

  socket.on("info", message=>{
    console.log("started uploading file")
    socket.broadcast.emit("info", message)
  });

  socket.on("disconnect", () => {
    console.log("user disconnected");
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment