Koa.js Multer Uploading Files with Validation of File Extension Filters and File Limits in Browser Using koa-multer Library Full Project For Beginners


Welcome folks today in this blog post we will be uploading files with validation of file extension and file limits in browser using koa-multer library.All the full source code of the application is given below.




Get Started




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



npm i @koa/multer multer



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






const multer = require('@koa/multer')

//Options to limit file size and file extension
const upload = multer({
        dest: '../avatars',
        limits: {
            fileSize: 1024*1024
        fileFilter(ctx, file, cb) {
            if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
                return cb(new Error('Please upload a World document'))
            cb(undefined, true)

//The last callback should handle the error from multer
        .post('/upload', upload.single('upload'), async (ctx) => {
            ctx.status = 200
        }, (error, ctx) => {
            ctx.status = 400
            ctx.body = error.message

Leave a Reply