Search code examples
javascriptnode.jsformidable

TypeError: Cannot read property 'path' of undefined in Node js while uploading file


I am new to node js.

I was trying to upload a file, it is showing some path error. Below is my code.

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

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        console.log(files);
      var oldpath = files.filetoupload.path;
      var newpath = '/var/www/html/Node-Js/img/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);

Here I have installed the formidable module.It's installed. I am getting this below error, please have a look.

/var/www/html/Node-Js/file_upload.js:11
      var oldpath = files.filetoupload.path;
                                       ^

TypeError: Cannot read property 'path' of undefined
    at /var/www/html/Node-Js/file_upload.js:11:40
    at IncomingForm.<anonymous> (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:107:9)
    at emitNone (events.js:106:13)
    at IncomingForm.emit (events.js:208:7)
    at IncomingForm._maybeEnd (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:557:8)
    at Object.end (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:247:12)
    at IncomingMessage.<anonymous> (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:132:30)
    at emitNone (events.js:106:13)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)


Solution

  • You are getting null{} in the console.log(files) is the reason behind this particular error. Filesis coming null so the files.filetoupload will be undefined and that's why files.filetoupload.path can't be found. I would say please find why the files is coming null. Once you will be started getting data in files this error will be solved.