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
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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 router .post('/upload', upload.single('upload'), async (ctx) => { ctx.status = 200 }, (error, ctx) => { ctx.status = 400 ctx.body = error.message }) }) |