首页 > 解决方案 > TypeError:上传文件时无法读取Node js中未定义的属性“路径”

问题描述

我是节点 js 的新手。

我试图上传一个文件,它显示了一些路径错误。下面是我的代码。

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);

在这里我已经安装了强大的模块。它已经安装了。我收到以下错误,请看一下。

/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)

标签: javascriptnode.jsformidable

解决方案


你得到null{}console.log(files)这个特定错误背后的原因。Files即将为空,因此files.filetoupload将是未定义的,这就是为什么files.filetoupload.path找不到。我会说请找出为什么会files为空。一旦您开始在文件中获取数据,此错误将得到解决。


推荐阅读