- Koa.js - Resources
- Koa.js - Scaffolding
- Koa.js - Logging
- Koa.js - RESTful APIs
- Koa.js - Database
- Koa.js - Caching
- Koa.js - Compression
- Koa.js - Authentication
- Koa.js - Sessions
- Koa.js - Cookies
- Koa.js - Static Files
- Koa.js - File Uploading
- Koa.js - Form Data
- Koa.js - Templating
- Koa.js - Cascading
- Koa.js - Error Handling
- Koa.js - Redirects
- Koa.js - Response Object
- Koa.js - Request Object
- Koa.js - HTTP Methods
- Koa.js - URL Building
- Koa.js - Routing
- Koa.js - Generators
- Koa.js - Hello World
- Koa.js - Environment
- Koa.js - Overview
- Koa.js - Home
Koa.js Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Koa.js - File Uploading
Web apppcations need to provide the functionapty to allow file uploads. Let us see how we can receive files from the cpents and store them on our server.
We have already used the koa-body middleware for parsing requests. This middleware is also used for handpng 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.
html head title File uploads body form(action = "/upload" method = "POST" enctype = "multipart/form-data") span input(type = "text" name = "name" placeholder = "Name") span input(type = "file" name = "image") span 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 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.psten(3000);
When you run this, you get the following form.
When you submit this, your console will produce the following output.
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.
Advertisements