Koa.js - File Uploading


Web applications need to provide the functionality to allow file uploads. Let us see how we can receive files from the clients and store them on our server.

We have already used the koa-body middleware for parsing requests. This middleware is also used for handling file uploads. Let us create a form that allows us to upload files and then save these files using Koa. First create a template named file_upload.pug with the following contents.

      title File uploads
      form(action = "/upload" method = "POST" enctype = "multipart/form-data")
            input(type = "text" name = "name" placeholder = "Name")
            input(type = "file" name = "image")
            input(type = "submit")

Note that you need to give the same encoding type as above in your form. Now let us handle this data on our server.

var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-body');
var app = koa();

//Set up Pug
var Pug = require('koa-pug');
var pug = new Pug({
   viewPath: './views',
   basedir: './views',
   app: app 

//Set up body parsing middleware
   formidable:{uploadDir: './uploads'},    //This is where the files would come
   multipart: true,
   urlencoded: true

var _ = router(); //Instantiate the router

_.get('/files', renderForm);
_.post('/upload', handleForm);

function * renderForm(){

function *handleForm(){
   console.log("Files: ", this.request.body.files);
   console.log("Fields: ", this.request.body.fields);
   this.body = "Received your data!"; //This is where the parsed request is stored



When you run this, you get the following form.

File Upload Form

When you submit this, your console will produce the following output.

File Console Screen

The files that were uploaded are stored in the path in the above output. You can access the files in the request using this.request.body.files and the fields in that request by this.request.body.fields.