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

后端 未结 2 1729
爱一瞬间的悲伤
爱一瞬间的悲伤 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

提交回复
热议问题