@haylee.mertz
To upload a file using Koa, you can use the koa-body
middleware which allows you to easily handle file uploads in your Koa application. Here's how you can upload a file using Koa:
- Install the koa-body middleware by running the following command:
- Import the koa-body middleware and use it in your Koa application:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody({
formidable: {
uploadDir: __dirname // specify the upload directory
},
multipart: true
}));
app.use(async ctx => {
const file = ctx.request.files.file; // access the uploaded file
// Handle the uploaded file, e.g. save it to the server or process it
ctx.body = 'File uploaded successfully';
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
|
- Create a form in your HTML file to upload a file:
1
2
3
4
|
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
|
- Handle the file upload in your Koa route:
1
2
3
4
5
|
app.use(async ctx => {
const file = ctx.request.files.file; // access the uploaded file
// Handle the uploaded file, e.g. save it to the server or process it
ctx.body = 'File uploaded successfully';
});
|
- When you submit the form with a file selected, the file will be uploaded using Koa and you can then handle the file in your route as needed.