How to connect formidable file upload to socket.io in Node.js

后端 未结 2 1718
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 23:00

I am node beginner and I am trying to set up a multifile image upload through formidable which will have a progress bar and also a callback after each upload which will dyna

相关标签:
2条回答
  • 2020-12-28 23:07

    I used node-formidable v1.0.14 and socket.io 1.0.0-pre.

    When the clients send a request a connection will be made and the server will create a room for this client based on his session id for example.

    Afterwards in the progress event we will broadcast the percentage to one client in the room.

    Here you can find more info about rooms: https://github.com/LearnBoost/socket.io/wiki/Rooms

    Server app.js (main, on startup):

    io.on('connection', function (socket) {
      console.log('CONNECTED');
      socket.join('sessionId');
    });
    

    Server POST:

    form.on('progress' , function (bytesRecieved , bytesExpected) {
      console.log('received: ' + bytesRecieved);
      io.sockets.in('sessionId').emit('uploadProgress', (bytesRecieved * 100) / bytesExpected);
    });
    

    Client:

    var socket = io.connect('http://localhost:9000');
    socket.on('uploadProgress' , function (percent){
      alert(percent);
    });
    

    When you want to work with sessions this might help: http://www.danielbaulig.de/socket-ioexpress/#comment-11315

    0 讨论(0)
  • 2020-12-28 23:11

    this should work for you

    form.addListener('progress' , function(bytesRecieved , bytesExpected){
      io.sockets.on('connection', function (socket) {
       socket.emit('uploadProgress', ((bytesRecieved * 100)/bytesExpected));
      });
     });
    

    and on the client side:

    script(src='/socket.io/socket.io.js')  // thats jade, but link to the .js anyway you want
     var socket = io.connect('http://localhost');
      socket.on('uploadProgess' , function(percent){
       $('#percent').text(percent); 
     });
    
    0 讨论(0)
提交回复
热议问题