When I set up my form without specifying an enctype
, Firefox automatically sets it to application/x-www-form-urlencoded
and req.body
contains a nice, JSON representation of all the parameters entered into the form. But when I change the enctype to multipart/form-data
req.body
is suddenly empty.
This is my form:
<form action="/create" method="post" enctype="multipart/form-data">
<fieldset>
<div>
<label>Category:</label>
</div>
<div>
<select name="category">
<option value="standard">Standard</option>
<option value="custom">Custom</option>
</div>
<div>
<input type="text" name="description">
</div>
<div>
<label>User ID:</label>
</div>
<div>
<input type="text" name="userid">
</div>
<div>
<input type="submit" value="Go">
</div>
</fieldset>
</form>
Doing a console.log(JSON.stringify(req.body, null, 2));
prints out an empty object when enctype
is multipart/form-data
and when enctype
is not specified, it prints out something like:
{
category: "standard",
userid: "foo"
}
Any reason this is happening?
Try use busboy-body-parser to retrieve the request body parameters and the files.
start.js
var bodyParser = require('body-parser');
var busboyBodyParser = require('busboy-body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json());
//parse multipart/form-data
app.use(busboyBodyParser());
controllers/someController.js
someAction: function(req,res){
if(req.method == "POST"){
res.end(JSON.stringify(req.body)+JSON.stringify(req.files));
}
}
//{"text":"testx"}{"anexo":{"data":{"type":"Buffer","data":.... }}}
//req.body = {"text":"testx"}
//req.files = {"anexo":{"data":{"type":"Buffer","data":.... }}}
views/someController/someAction.html
<form method="post" id="multipart" enctype="multipart/form-data">
<input type="text" id="text1" name="text" value="testx" />
<input type="file" id="anexo" name="anexo" />
<input type="submit" value="Enviar" />
</form>
To create a file uploaded, you need work if the stream, for example:
/* file props
{
"data":{"type":"Buffer","data":.... },
"fieldname":"anexo",
"originalname":"images (1).jpg",
"encoding":"7bit",
"mimetype":"image/jpeg",
"destination":"c:\\live\\sources\\uploads\\",
"filename":"eventclock_images (1)_1443706175833.jpg",
"path":"c:\\live\\sources\\uploads\\eventclock_images(1)_1443706175833.jpg",
"size":9986
}
*/
var fileStream = fs.createWriteStream(file.path);
fileStream.write(file.data);
fileStream.end();
fileStream.on('error', function (err) {
//console.log("error",err);
});
fileStream.on('finish', function (res) {
//console.log("finish",res);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With