How to parse multipart/form-data body with Koa?

eightyfive picture eightyfive · Nov 17, 2015 · Viewed 25.1k times · Source

Because I spent some (too much) time figuring out this simple requirement. I am documenting here the way to achieve multipart/form-data body parsing with Koa.

In my case, the reason of the confusion was the number of alternatives available out there:

And I wanted to find the most minimalist/close to express/koa/node way/philosophy of doing things.

So here it is. Below. In accepted answer. Hope this helps.

Answer

silkAdmin picture silkAdmin · Apr 27, 2016

For Koa2, you can use async-busboy as other solutions dont support promises or async/await.

Example from the docs:

import asyncBusboy from 'async-busboy';

// Koa 2 middleware
async function(ctx, next) {
  const {files, fields} = await asyncBusboy(ctx.req);

  // Make some validation on the fields before upload to S3
  if ( checkFiles(fields) ) {
    files.map(uploadFilesToS3)
  } else {
    return 'error';
  }
}