this.socket = io(environment.socketUrl, {
"transports": ["polling", "websocket"]
});
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);
}
<input type="file" (change)="assignName(document); handleChange($event.target.files)" />
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");
});
});