0

I have problems when i upload an image to my server, when i do that i want to emit this event to the room "1room"

 `io.sockets.in("1room").emit('image_added','OK');`

the problem is, the event doesnt fired on the client, but if i reload the page yes, the event is fired.

HTML

 <form ref='uploadForm' 
      id='uploadForm' 
      action='http://localhost:3000/upload' 
      method='post' 
      encType="multipart/form-data">
       <input type="file" name="sampleFile" />
       <input type='submit' value='Upload!' />
 </form>     

SERVER

io.sockets.on('connection', function(socket){

   socket.join("1room");

});

    app.post('/upload', function(req, res) {

      if (!req.files)
        return res.status(400).send('No files were uploaded.');

      let sampleFile = req.files.sampleFile;

      sampleFile.mv('/xampp2/htdocs/pic.jpg', function(err) {

        if (err)
          return res.status(500).send(err);

     if (res.status(200)){
            io.on('connection', function(socket){
            io.sockets.in("1room").emit('image_added','OK'); 
    });

        }

      });

    });

CLIENT

socket.on('image_added', function(status) {

   alert(status);

});
2
  • Why are you using io.on('connection' again in the post request? Commented Mar 1, 2017 at 16:06
  • Also, Don't use Stackoverflow for question that can be fixed with a couple of more searches and or a little more effort. Commented Mar 1, 2017 at 16:10

2 Answers 2

2

Change this:

 if (res.status(200)){
    io.on('connection', function(socket){
        io.sockets.in("1room").emit('image_added','OK'); 
    });
}

to this:

 res.status(200);
 io.sockets.in("1room").emit('image_added','OK');  

You can't put an io.on('connection', ...) inside an app.post() nor would you ever want to. The event does not occur while that route is being processed. Instead, you just want to broadcast to all connection clients in that room with io.sockets.in("1room").emit('image_added','OK');

In addition, there's no point to if (res.status(200)) because that is always true since res.status() just returns the res object.

Sign up to request clarification or add additional context in comments.

Comments

0

simple you are only sending if there is brand new connection event fire.

io.sockets.in("1room").emit('image_added','OK')

remove the connection event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.