NodeJs Image upload with Multer

Multer is a node.js middleware for handling multipart/form-data , which is primarily used for uploading files.

I once published an article on how to upload images to cloudinary with a React App but what if we wanted to upload images on our own Nodejs server? This is what I’ll be covering in this tutorial. I’ll be showing You how to upload images using Multer and also how to process images using Sharp. By the end of this tutorial, you’ll be able to implement this into your existing or new projects.

Prerequisites

  • Basic understanding of javascript
  • Basic knowledge of NodeJs/Express
  • The latest version of nodeJs installed on your machine
  • Postman

1. Setting up our Project

1.1 Installing Node

node -v

1.2 Create a folder directory

mkdir image-upload-with-multer
cd image-upload-with-multer

2. Project initialization

2.1 Create a package.json file

npm init -y

2.2 Install dependencies and dev-dependencies

npm i express multer sharp

npm i -D nodemon

"dev":"nodemon app.js"

3. Setting up our Server

3.1 Basic server setup

const express = require('express')

const multer = require('multer')

const sharp = require('sharp')

const port = process.env.PORT || 5000

const app = express()
app.use(express.json())

app.listen(port, () => {
console.log('Server is running on port '+ port)
})

npm run dev

4. Multer

4.1 Configuring Multer

const upload = multer({

limits: {

fileSize: 1000000

},

fileFilter(req, file, cb) {

if(!file.originalname.match(/\.(jpg|jpeg|png)$/)) {

return cb( new Error('Please upload a valid image file'))

}

cb(undefined, true)

}
})

5. Image upload route

app.post('/image', upload.single('upload'), async (req, res) => {

try {

await sharp(req.file.buffer).resize({ width: 250, height: 250 }).png().toFile(__dirname + `/images/${req.file.originalname}`)

res.status(201).send('Image uploaded succesfully')

} catch (error) {

console.log(error)

res.status(400).send(error)

}

})

6. Testing with Postman

localhost:5000/image

7. Conclusion