5

My code shows a simple upload form (node-formidable and node.js). I am using socket.io to update the client on it's current upload file progress. My problem is that I currently emit the progress update to every clients. As an example, if I start an upload with clientA, then connect to the website with clientB, clientB will see the exact same progress bar as clientA. Normally, clientA and clientB should be different, with their own respective progress bars, linked only with their respective uploads.

This is my app.js file

// Required modules
var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    fs = require('fs-extra');

// Path to save file, server side
var savePath = "./uploadedFiles/";

// Loading index.html
var server = http.createServer(function(req, res) {
    // Form uploading Process code
    //Upload route
    if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
        // creates a new incoming form. 
        var form = new formidable.IncomingForm();

        // set the path to save the uploaded file on server
        form.uploadDir = savePath;

        // updating the progress of the upload
        form.on('progress', function(bytesReceived, bytesExpected) {
            io.sockets.in('sessionId').emit('uploadProgress', (bytesReceived * 100) / bytesExpected);
        });

        // parse a file upload
        form.parse(req, function (err, fields, files) {
            res.writeHead(200, { 'content-type': 'text/plain' });
            res.write('Upload received :\n');
            res.end(util.inspect({ fields: fields, files: files }));
        });
        form.on('end', function (fields, files) {
            /* Temporary location of our uploaded file */
            var temp_path = this.openedFiles[0].path;
            /* The file name of the uploaded file */
            var file_name = this.openedFiles[0].name;
            /* Files are nammed correctly */
            fs.rename(temp_path, savePath + file_name, function(err) {
                if ( err ) console.log('ERROR: ' + err);
            });
        });
        return;
    }

    fs.readFile('./index.html', 'utf-8', function(error, content) {
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    });
});

// socket.io
var io = require('socket.io').listen(server);

io.on('connection', function (socket) {
  socket.join("sessionId");
});

server.listen(8080);

This is my index.html file

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Socket.io</title>
    </head>

    <body>
        <h1>Test d'upload</h1>

        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = io.connect('http://localhost:8080');
            socket.on('uploadProgress' , function (progress){
                document.getElementById("currentProgress").value = progress;
            });
        </script>

        <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="upload" multiple="multiple"><br>
        <input type="submit" value="Upload">
        </form>

        <p><progress id="currentProgress" value="0" max="100"></progress></p>
    </body>
</html>

I do not have more code than this. I am new to node.js and socket.io, so I am not sure about the interactions between them and between the client and server.

How can I change my code to update only the right client?

Thank you anyway for your time.

1 Answer 1

1

a suggestion there is a basic way

socketIO.sockets.socket(this.socketid).emit(<event>, dataObj);

if your function is inside your socket code...otherwise I will often do something like this

connection.query("select socketid from websocket_sessions  where user_id=" + data.form.user_id, function(err, users) {
  socketIO.sockets.socket(users[0].socketid).emit(<event>, dataObj);
});

where I am always updating or a

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

1 Comment

I tried to use this in my provided code and it did not work. How do you get a user id? Do you have a simply example that fits my code? Thank you.

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.