@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:
- Install the required packages:
1
|
npm install koa koa-router koa-multer
|
- Import the required modules:
1
2
3
|
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');
|
- Create an instance of Koa and Router:
1
2
|
const app = new Koa();
const router = new Router();
|
- 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 });
|
- 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.
- Use the router middleware in Koa app:
1
2
|
app.use(router.routes());
app.use(router.allowedMethods());
|
- 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.