上载文件时无法读取属性“路径”

时间:2018-07-25 08:04:13

标签: node.js

嗨,我只是想学习Node js,我想将文件上传到计算机的其他位置,但是我遇到了一些问题...这是我的代码...

var http = require('http');
var fs = require('fs');
var formidable = require('formidable');
http.createServer(function(req,res){
    if(req.url == '/upload'){
        var form = new formidable.IncomingForm();
        form.parse(req,function(err,fields,files){
            var oldpath = files.filetoupload.path;
            var newpath = 'E:/Node/ResumeUpload/' + files.filetoupload.name;
            fs.rename(oldpath,newpath,function(err){
                if(err) console.log(err);
                res.write('File uploaded sucessfully to ' + newpath);
                res.end();
            }) 
        });
    }
    else{
        fs.readFile('FileUpload.html',function(err,data){
            res.writeHead(200,{'Content-Type' : 'text/html'});
            res.write(data);
            res.end();
        });
    }
}).listen(9090);

但是问题是它显示了如下错误

var oldpath = files.filetoupload.path;
TypeError: Cannot read property 'path' of undefined
    at E:\Node\FileUploading.js:8:46
    at IncomingForm.<anonymous> (E:\Node\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 (E:\Node\node_modules\formidable\lib\incoming_form.js:557:8)
    at E:\Node\node_modules\formidable\lib\incoming_form.js:238:12
    at WriteStream.<anonymous> (E:\Node\node_modules\formidable\lib\file.js:79:5)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
    at WriteStream.emit (events.js:208:7)

有人可以建议这个问题的原因是什么... !!

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在nodejs中使用try模块覆盖器,可以上传文件,可以看到:Multer

//install multer
$ npm install --save multer