Todd Davies
Todd Davies

Reputation: 5522

Node.js file upload not working

I'm building a super simple file server with node.js.

I'm using dotcloud to host my server, which is accessible here.

When I try to upload a file (with the correct password), my code returns 'Error, incorrect password!'. Take a look at the code below, and I'll explain why:

var success = false;
        var form = new formidable.IncomingForm();
        form.parse(req, function(err,fields, files) {
            console.log("Password: " + fields.password);
    if(fields.password!="poop") {
        return;
    }
       fs.rename(files.upload.path, files.upload.name, function (err) {  });
       success = true;
          res.writeHead(200, {'content-type': 'text/plain'});
          res.write('received upload:\n\n');
          res.end();
        });
        req.on('end', function() {
          // empty 200 OK response for now
      if(success) {
              res.writeHead(302, { 'location': '/' });
          } else {
      res.writeHead(200, {'content-type': 'text/plain'});
              res.write('Error, incorrect password!\n');
      }
          res.end();
        });

I think my code is failing at 'fs.rename(files.....)' as then the success variable isn't set to true. My code works on my local node.js installation, do I need to request write permissions from dotcloud or something?

Upvotes: 1

Views: 593

Answers (1)

jpetazzo
jpetazzo

Reputation: 15511

I believe that the end event for the HTTP request is emitted before formidable parses the form.

The exact order of event dispatch is not defined in the Node.js documentation; so it could be that depending on the Node.js version and/or platform, they end up being processed in different orders.

In that case, if that happens, success is then false and you send the reply before even actually parsing the form.

Maybe you should handle errors in the form parsing function instead?

Upvotes: 0

Related Questions