Node.js upload file

Formidable module has been used to upload file in Node.js

Terminal command to install Formidable module

npm install formidable

Now create project folder in use below files

index.html

<html>
<title>
File uploading using formidable module
</title>
<body>
<form action="fileupload" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
</body>
</html>

app.js

var http = require('http');
var url = require('url');
var fs = require('fs');
var formidable = require('formidable');


http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;

  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.uploadDir='./temp';
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = './upload/' + files.filetoupload.name;
      fs.renameSync(oldpath, './temp/'+files.filetoupload.name);
      fs.rename('./temp/'+files.filetoupload.name, newpath, function (err) {

        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
 return null;
  }



  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    } 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Terminal command to start server

node app.js

Screenshot of file uploading using node.js with formidable module

Leave a Comment