@arnoldo.moen
To receive a zip file in a Koa server, you need to configure the server to handle file uploads using a middleware like koa-body
, and then implement the necessary logic to handle the uploaded file. Here is a step-by-step guide to achieve this:
- Install koa-body package using npm or yarn.
- Import necessary modules in your server file.
1
2
3
4
|
const Koa = require('koa');
const koaBody = require('koa-body');
const Router = require('koa-router');
const fs = require('fs');
|
- Create a Koa app and router object.
1
2
|
const app = new Koa();
const router = new Router();
|
- Configure the middleware to handle file uploads.
1
2
3
4
5
6
|
app.use(koaBody({
multipart: true, // Enable multipart/form-data parsing
formidable: {
uploadDir: __dirname + '/uploads' // Specify the upload directory
}
}));
|
- Define a route to handle the file upload.
1
2
3
4
5
6
7
8
9
10
11
|
router.post('/upload', (ctx) => {
const file = ctx.request.files.file; // Access the uploaded file
// Read the file stream and write it to a file
const reader = fs.createReadStream(file.path);
const stream = fs.createWriteStream(__dirname + '/uploads/' + file.name);
reader.pipe(stream);
// Respond with a success message
ctx.body = 'File uploaded successfully';
});
|
- Apply the router middleware to the app.
1
2
|
app.use(router.routes());
app.use(router.allowedMethods());
|
- Start the server to listen on a port.
1
2
3
|
app.listen(3000, () => {
console.log('Server running on port 3000');
});
|
Make sure to create an uploads
folder in the same directory as your server file to save the uploaded files.
Now your Koa server is configured to receive a zip file. You can send a file using a POST request to the /upload
endpoint as a multipart/form-data
form. The file will be saved in the uploads
folder.