Koa.js Tutorial to Upload Files on Server Using Formidable Library Using Javascript Full Project For Beginners

 

Welcome folks today in this blog post we will be uploading files on the server in koa.js using formidable library in javascript.All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to install the below library using the npm command as shown below

 

 

npm i formidable

 

 

After installing this library you need to make an index.js file and copy paste the following code

 

 

index.js

 

 

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
app.use(bodyParser({
   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(){
   this.render('file_upload');
}

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
}

app.use(_.routes()); 
app.listen(3000);

 

See also  Build a Javascript Image Compressor using HTML5 Canvas & File API Before Uploading to Server Full Project For Beginners

 

 

And now make a index.pug file and copy paste the following code

 

 

index.pug

 

 

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

Leave a Reply