AngularJS : How to send files via websocket?

2019-07-22 19:15发布

问题:

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 user can send "attachments" to each other. FYI, I came across this link which says few point but I need more clarity.

My questions:

  1. What is the server-side requirement there for its implementation?
  2. Can someone provide a little elaborated answer? More codes rather than words are highly appreciated.
  3. Do I need to use use ng-file-upload for the same, DEMO
  4. Any relevant link for this question

UPDATE 1:

I tried implementing below code:

var input = document.querySelector('input[type=file]');

function readFile(event) {
    var ws_msg =  {content: event.target.result };
    // Here I call the ws.send method 
    send_chat_message($scope.sender, $scope.receiver , ws_msg );
}

function changeFile() {
    var file = input.files[0];
    var reader = new FileReader();
    reader.addEventListener('load', readFile);
    reader.readAsText(file);
}

input.addEventListener('change', changeFile);

Selecting a file automatically tries to send it over ws but for some weird reason, the WS connection is getting closed immediately.

回答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).

  1. Create a folder and do a npm install --save ws
  2. Create a server.js file and add below code.

            const WebSocket = require('ws');
    
            const wss = new WebSocket.Server({ port: 8080 });
    
            wss.on('connection', function connection(ws) {
              ws.on('message', function incoming(message) {
                console.log('received: %s', message);
              });
    
              ws.send('something');
            });
    
  3. run node server using node server.js, your websocket server is up on localhost:8080

  4. 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 = new WebSocket('ws://localhost:8080');
    
                socket.addEventListener('open', function (event) {
                    socket.send('Hello Server!');
                });
    
    
            function readFile(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 );
            }
    
            function changeFile() {
                var file = input.files[0];
                var reader = new FileReader();
                reader.addEventListener('load', readFile);
                reader.readAsText(file);
            }
    
            input.addEventListener('change', changeFile);
    
  5. 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:

            const WebSocket = require('ws');
            const fs = require('fs');

            const wss = new WebSocket.Server({ port: 8080 });


            wss.on('connection', function connection(ws) {
              ws.on('message', function incoming(message) {
                let data =  new Buffer(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 = new WebSocket('ws://localhost:8080');

                socket.addEventListener('open', function (event) {
                    socket.send('Hello Server!');
                });

            function readFile(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 );
            }

            function changeFile() {
                var file = input.files[0];
                var reader = new FileReader();  
                reader.addEventListener('load', readFile);
                reader.readAsArrayBuffer(file);
            }

            input.addEventListener('change', changeFile);