Google News
logo
Koa.js - Interview Questions
How does Koa.js handle file uploads?
In Koa.js, handling file uploads typically involves using a middleware that can parse and handle the incoming multipart/form-data requests, which are commonly used for file uploads. One popular middleware for handling file uploads in Koa.js is koa-body.

Here's a step-by-step guide on how you can handle file uploads in Koa.js using the koa-body middleware:

1. Install koa-body : Begin by installing the koa-body middleware using npm or yarn.
npm install koa-body?

2. Use koa-body Middleware in Your Koa Application : Import and use the koa-body middleware in your Koa application. Make sure to use it before your route handlers to enable the parsing of incoming requests.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();

// Use the koa-body middleware for handling file uploads
app.use(koaBody({ multipart: true }));

// Your route handlers go here

// Start the Koa application
const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});?

The koa-body middleware, when configured with multipart: true, enables the handling of multipart/form-data requests, including file uploads.
3. Handle File Uploads in Your Route Handlers : Access the uploaded files in your route handlers using the ctx.request.files property. This property contains an object where each key is the name of the file input field, and the corresponding value is an array of file objects.
app.use(async (ctx, next) => {
  if (ctx.method === 'POST' && ctx.path === '/upload') {
    const files = ctx.request.files; // Access uploaded files

    // Process uploaded files (e.g., save to disk, database, etc.)
    // ...

    ctx.body = 'File upload successful';
  } else {
    await next();
  }
});?

In the example above, the route handler checks if the request method is POST and the path is '/upload'. If so, it retrieves the uploaded files from ctx.request.files and processes them as needed.


4. HTML Form for File Upload : In your HTML form, set the enctype attribute to "multipart/form-data" to enable file uploads. Also, use the type="file" input field to allow users to select files.
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="myFile">
  <button type="submit">Upload File</button>
</form>?

This is a simple example of an HTML form that allows users to select a file and submit it to the '/upload' endpoint.
Advertisement