尝试上传文件时,NodeJS引发错误

时间:2018-10-30 20:18:46

标签: node.js

我有这段代码,我试图从字面上做到,以便用户可以上传文件,并将文件添加到目录中,但是我遇到了某种问题,文件被转储到节点的目录中文件用完了,它崩溃了。我在我的本地机器上运行它以进行测试以运行win10。

我确实收到此错误消息:

var oldpath = files.filetoupload.path;
                                       ^

TypeError: Cannot read property 'path' of undefined


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) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:\Users\Bob\Documents\Test\Files' + 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);

0 个答案:

没有答案