Reputation: 3428
I'm using body-parser, express and multer
in my NodeJS app.
I need to upload Image and few text fields in signup form. I'm using multer
for this, I tried exactly the same thing suggested here
But I get empty object in req.body
.
Files are being created in the destination folder, but req.files.forEach
methods logs empty result.
Here is my code:
Html front end code
<form id="form" enctype="multipart/form-data" action="/profile" method="post" >
<label>Name</label>
<input type="text" placeholder=" Name" name="name" id="name" class="form-control">
<label>Logo</label>
<input type="file" placeholder="Logo" name="logo" id="logo" class="form-control">
<button id="addform" type="submit" class="btn btn-primary">Add Profile</button>
</form>
Server Side Code:
app.post('/profile', function(req, res) {
var storage = multer.diskStorage({
destination: __dirname+'/file/uploads/'
});
var upload = multer({ storage : storage}).any();
upload(req,res,function(err) {
if(err) {
console.log(err);
return res.end("Error uploading file.");
} else {
console.log(req.body);
console.log(req.files);
req.files.forEach( function(f) {
console.log(f);
// and move file to final destination...
});
res.end("File has been uploaded");
}
});
});
Log output in Node:
{}
[]
Upvotes: 2
Views: 7894
Reputation: 1179
Please recheck your form and make sure you have added name attribute to your input fields. I encountered same issue, and similarly was trying to find, but when reviewed multer documentation and found that it doesn't block req.body than I checked my form and found my other fields were not having name
attribute only id was there.
Upvotes: 0
Reputation: 1424
Try moving your Multer outside of the req body and try including filename parameter. I have modified your code.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname+'/file/uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
//passing multer as middleware
app.post('/profile',upload.any(), function(req, res) {
console.log(req.body)
});
Upvotes: 5