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

Member

by darion , in category: Javascript , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a year ago

@darion 

To parse multipart/form-data body with Koa, you can use the koa-multer package.


Here are the steps to parse multipart/form-data body with Koa:

  1. Install the required packages:
1
npm install koa koa-router koa-multer


  1. Import the required modules:
1
2
3
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');


  1. Create an instance of Koa and Router:
1
2
const app = new Koa();
const router = new Router();


  1. Set up the storage for multer:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads'); // Set the destination folder for uploaded files
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname); // Set the filename of the uploaded files
  }
});

const upload = multer({ storage: storage });


  1. Define a route that handles multipart/form-data requests:
1
2
3
4
router.post('/upload', upload.single('file'), async (ctx) => {
  console.log(ctx.req.file); // File details can be accessed using ctx.req.file
  ctx.body = 'File uploaded successfully';
});


In this example, the route /upload is set up to handle POST requests with a file input field named file. The upload.single() middleware is used to parse the file from the request.

  1. Use the router middleware in Koa app:
1
2
app.use(router.routes());
app.use(router.allowedMethods());


  1. Start the Koa server:
1
2
3
app.listen(3000, () => {
  console.log('Server running on port 3000');
});


With these steps, you have successfully set up Koa to parse multipart/form-data body using the koa-multer package.