2016-09-20 266 views
4

这里是我的问题,我有一个表单可以插入文件和字段,但我只接收文件而不是参数test!为什么?Node.js,multer和req.body为空

这是我的代码:

app.js:

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 
var port = 8000; 
var multer = require('multer'); // v1.0.5 
var storage =   multer.diskStorage({ 
  destination: function (req, file, callback) { 
    callback(null, './uploads'); 
  }, 
  filename: function (req, file, callback) { 
    callback(null, file.originalname.substring(0,file.originalname.lastIndexOf('.')) + '-' + Date.now() + file.originalname.substring(file.originalname.lastIndexOf('.'),file.originalname.length)); 
  } 
}); 
var upload = multer({ storage : storage}).single('fileUpload'); 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true})); 

app.post('/api/upload',function(req,res){ 
    console.log(req.body); 
    upload(req,res,function(err) { 
        if(err) { 
            return res.end("Error uploading file."); 
        } 
        res.end("File is uploaded"); 
    }); 
}); 

app.listen(port, function() { 
    console.log('Express server inizializzato sulla porta ' + port); 
}); 

的index.html:

<html> 
    <head> 
     <title>Test upload</title> 
    </head> 
    <body> 
     <form name="form" action="http://localhost:8000/api/upload" method="post" enctype="multipart/form-data"> 
      <input type="text" name="test" /> 
      <input type="file" name="fileUpload" /> 
      <input type="submit" value="invia" /> 
     </form> 
    </body> 
</html> 

有人能帮助我吗?

+0

你尝试'REQ。 body'? – abdulbarik

+0

@abdulbarik:是的,我尝试返回req.body,但返回{} – Filippo1980

+0

它可能有助于http://stackoverflow.com/questions/35847293/uploading-a-file-and-passing-a-additional-parameter-多重 – abdulbarik

回答

5

2017年更新

From Readme

注意req.body可能没有被完全填充呢。它取决于客户端将字段和文件传输到服务器的顺序。

我解决我的问题,通过在前端扭转我的表单对象属性的顺序:

var newFormObj = new FormData(); 
    newFormObj.append('internalUserID', internalUserID); 
    newFormObj.append('listingImage', this.binaryImages[image]); 

在后端:

var storage = multer.diskStorage({ 
    destination: function (req, file, cb) { 
    console.log(req.body.internalUserID) // YAY, IT'S POPULATED 
    cb(null, 'listing-pics/') 
    },      
    filename: function (req, file, cb) { 
    cb(null, file.fieldname + '-' + Date.now()) 
    }      
});      

var upload = multer({ storage: storage }); 
+1

是的,它工作:thumbsup: – Nigilan

+0

为什么我得到一个空req.body? – leafiy

3

我解决在后函数结束运动req.body

app.post('/api/upload?:test',function(req,res){ 

    upload(req,res,function(err) { 
        if(err) { 
            return res.end("Error uploading file."); 
        } 
        res.end("File is uploaded"); 
    console.log(req.body); 

    }); 
}); 

如果有人能告诉我,为什么我会乐意学习新的东西!但是,现在,我解决了!

+0

它工作完美,但为什么?有人可以解释这一点吗? –

+1

Hei,body-parser不处理多部分/表单数据体,但是multer确实。这就是为什么你只能访问上传函数中的req.body。 – Angie

+0

谢谢@Angie您的回答我的怀疑! – Filippo1980