I went through the same investigation than you and here are other ways to achieve multipart/form-data
body parsing with Koa.
co-busboy:
var koa = require('koa');
var parse = require('co-busboy');
const app = koa();
app.use(function* (next) {
// the body isn't multipart, so busboy can't parse it
if (!this.request.is('multipart/*')) return yield next;
var parts = parse(this),
part,
fields = {};
while (part = yield parts) {
if (part.length) {
// arrays are busboy fields
console.log('key: ' + part[0]);
console.log('value: ' + part[1]);
fields[part[0]] = part[1];
} else {
// it's a stream, you can do something like:
// part.pipe(fs.createWriteStream('some file.txt'));
}
}
this.body = JSON.stringify(fields, null, 2);
})
koa-body:
var koa = require('koa');
var router = require('koa-router');
var koaBody = require('koa-body')({ multipart: true });
const app = koa();
app.use(router(app));
app.post('/', koaBody, function *(next) {
console.log(this.request.body.fields);
this.body = JSON.stringify(this.request.body, null, 2);
});
In both cases you will have a response like:
{
"topsecret": 1,
"area51": {
"lat": "37.235065",
"lng": "-115.811117",
}
}
But personally, I prefer the way koa-body works. Plus, is compatible with other middleware like koa-validate.
Also, if you specify an upload dir to koa-body, it will save the uploaded file for you:
var koaBody = require('koa-body')({
multipart: true,
formidable: { uploadDir: path.join(__dirname, 'tmp') }
});
this.request
. – Riojas