尝试将文件上载到具有节点js的服务器时,req.files为空

时间:2014-07-11 11:01:05

标签: javascript html node.js file

HTML:

<form action="/uploadpic" method="post" enctype="multipart/form-data">
    <input type="file" data-clear-btn="true" name="image" id="new_pic" value="" placeholder="Choose File">
    <input type="submit" value="Add" style="width:30%">
</form>

的NodeJS:

app.post('/uploadpic', function(req,res) {
console.log(req.files);
console.log(req.body);});

我也用:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json())
app.use(express.bodyParser({uploadDir:'./uploads'}));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
在控制台中我得到:

{}
{}

我似乎不明白这里可能出现什么问题..谢谢!

2 个答案:

答案 0 :(得分:0)

BodyParser不包含文件上传。您需要使用multermultiparty之类的内容。

此外,Express(4.0+)不再与中间件捆绑在一起,因此您需要使用bodyparser进行POST请求。

答案 1 :(得分:0)

   var fs = require('fs');

    app.post('/uploadpic', function(req,res) {

    //req.files contains array of files iterate and get it
    //if it has only one. it is like object

    //here is the code for object

    if (req && req.files) {

     var contentType = req.files.file.type;    
     var fname = req.files.file.name;    
     var image_path = req.files.file.path;    
     fs.readFile(image_path, function (err, data) { 
      var data = data; //this is your data use this
     })

    }

})