I'm creating a form to upload an image and at the same time this form contains other fields. The problem is that when I try to get the form data with req.body
there an undefined. do you know why? it is not possible to get other input when using enctype="multipart/form-data"
?
Asked
Active
Viewed 3,675 times
2

Mazzy
- 13,354
- 43
- 126
- 207
-
Please, check if you not forget to use https://github.com/expressjs/body-parser – Alexander R. Jul 22 '15 at 10:53
-
I'm already using it – Mazzy Jul 22 '15 at 10:55
-
It's strange that body is undefined if you use body-parser in right way. Look here for solutions - http://stackoverflow.com/questions/5149545/uploading-images-using-node-js-express-and-mongoose – Alexander R. Jul 22 '15 at 11:13
-
Did you have any success using `multiparty`? – Philip O'Brien Jul 23 '15 at 13:37
1 Answers
4
You could use the multiparty module as follows
var multiparty = require('multiparty');
exports.parseForm = function (req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
//here you can read the appropriate fields/files
});
};
Also be sure you are setting the enctype
correctly in your html
<form role='form' method='post' enctype="multipart/form-data">
When I used this it was to submit multiple text fields, and a single image file, via the HTML form. Then in my parseForm
function I would bundle these into a single object to be saved to mongo as follows
form.parse(req, function(err, fields, files) {
var temp = fields;
temp.image = {};
temp.image.data = fs.readFileSync(files.image[0].path);
temp.image.contentType = 'image';
var product = new Product(temp);
product.save();
res.redirect('/');
});

Philip O'Brien
- 4,146
- 10
- 46
- 96