Angularjs : How To Send Files Via Websocket?
I am new to websocket and I have been assigned an existing working chat module which, for now, just sends messages to other users. I have been asked to integrate feature where a us
Solution 1:
I have tried below sample code. I have used https://github.com/websockets/ws for web-socket server. and in HTML/jS I have modified code like below works fine. Steps are below. (Hope you have node installed).
- Create a folder and do a npm install --save ws
Create a server.js file and add below code.
constWebSocket = require('ws'); const wss = newWebSocket.Server({ port: 8080 }); wss.on('connection', functionconnection(ws) { ws.on('message', functionincoming(message) { console.log('received: %s', message); }); ws.send('something'); });
run node server using node server.js, your websocket server is up on localhost:8080
In your browser js change code as below (you are using angular do the change accordingly later as per your requirement)
var input = document.querySelector('input[type=file]'); var socket = newWebSocket('ws://localhost:8080'); socket.addEventListener('open', function (event) { socket.send('Hello Server!'); }); functionreadFile(event) { var ws_msg = {content: event.target.result }; socket.send(ws_msg); // Here I call the ws.send method //send_chat_message($scope.sender, $scope.receiver , ws_msg ); } functionchangeFile() { var file = input.files[0]; var reader = newFileReader(); reader.addEventListener('load', readFile); reader.readAsText(file); } input.addEventListener('change', changeFile);
load your JS/HTML and upload a file you should see to console logs in your node server console.
UPDATE:
you can update your node js server code:
constWebSocket = require('ws');
const fs = require('fs');
const wss = newWebSocket.Server({ port: 8080 });
wss.on('connection', functionconnection(ws) {
ws.on('message', functionincoming(message) {
let data = newBuffer(message);
fs.writeFile('new.png', data, 'binary', function (err) {
if (err) {
console.log("error")
}
else {
console.log("done")
}
});
});
Reference:Create image from ArrayBuffer in Nodejs
ws.send('something');
});
And client(browser side js) code as:
var input = document.querySelector('input[type=file]');
var socket = newWebSocket('ws://localhost:8080');
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
functionreadFile(e) {
//var ws_msg = {content: event.target.result };var rawData = e.target.result;
socket.send(rawData);
// Here I call the ws.send method //send_chat_message($scope.sender, $scope.receiver , ws_msg );
}
functionchangeFile() {
var file = input.files[0];
var reader = newFileReader();
reader.addEventListener('load', readFile);
reader.readAsArrayBuffer(file);
}
input.addEventListener('change', changeFile);
Post a Comment for "Angularjs : How To Send Files Via Websocket?"