Reputation: 351
I am new to nodejs and i am trying to achieve file transfer from a server to a web-client. Say, a server's work is to take a screenshot and send it to the web-client I have achieved connection between the server and client through express and I am able to check to whether the client is connected, since I am using express and socket.io I was hoping to send the captured image through 'socket.broadcast.emit'
This is the code I am using:
sources.forEach(function (source) {
if(source.name === "Entire screen" || source.name === "Screen 1" ){
if(screenShotPath === ''){
screenShotPath = path.join(os.tmpdir(),'screenshot.jpeg');
}
console.log(screenShotPath);
io.sockets.on('connection', function(socket){
console.log('A new client is conencted');
socket.broadcast.emit('img', source.thumbnail.toPNG);
})
fs.writeFile(screenShotPath,source.thumbnail.toPNG(), function (err) {
if(err) return console.log(err.message);
shell.openExternal("file://"+screenShotPath);
var message = 'Saved SS to ' + screenShotPath;
screenshotMsg.textContent = message;
});
}
});
will this work? And can someone please tell me how to receive the sent stream? Is this the way to send the image and receive it in the web-client or is there a easier way to achieve this functionality?
Also. is there way to send the image between two servers? Say one server is taking the screenshot and I'll have to save this image in another system which is a server, is there a way to do this?
Upvotes: 1
Views: 7455
Reputation: 1610
You need to broadcast the base64 encoded image, then use data URI to display it.
const fs = require('fs');
const imgFile = fs.readFileSync(filePath);
const imgBase64 = new Buffer(imgFile).toString('base64');
socket.broadcast.emit('img', imgBase64);
socket.on('img', (data) => {
const imgTag = `<img src="data:image/png;base64, ${data}"/>` // inject into DOM
});
Upvotes: 6