Using formidable module

suggest change

Install the module and read the docs.

npm i formidable@latest

formidable@latest tracks whatever major version npm sees as latest, and the API has changed between majors. The server below is the callback form from the older docs. The placeholder do-smth was not JavaScript. An error is logged and the handler returns.

var formidable = require('formidable'),
    http = require('http'),
    util = require('util');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
      if (err) {
          console.error(err);
          res.writeHead(400, {'content-type': 'text/plain'});
          res.end('upload failed');
          return;
      }

      // Copy file from temporary place
      // var fs = require('fs');
      // fs.rename(file.path, targetPath, function (err) { ... });

      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));
    });

    return;
  }

  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(8080);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents