DEV Community


Posted on


how to upload image using multer and sharp

when I started my journey through the development world, I had some difficulties and reading documentation was one of them. So I had the idea of ​​writing about things I already learned that I had difficulty in the beginning

NOTE : I understand that you already have experience building servers using express.js and node development

about multer

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. IMPORTANT : Multer will not process any form which is not multipart (multipart/form-data).


npm install multer

about sharp

The typical use case of Sharp is to convert large images in common formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.


npm install sharp

project structure

├── index.js |main application file
├──uploads |image upload folder
└── resized |image resized upload folder
├── upload-config.js |multer configuration
├── node_modules | modules of application
├── package-lock.json |cache of package.json
├── package.json |lists the packages your project depends on

hands on code

For testing it is recommended that you use some API Testing program such as Insomia or Postman.

IMPORTANT: Don't forget to set Multipart Form Architecture in the request body in your API test program.

├── index.js

const express = require('express')
const multer = require('multer')
const sharp = require('sharp')
const storage = require('./upload-config')
const upload = multer(storage)
const path = require('path')
const fs = require('fs')
const app = express()

const router = new express.Router

router.get('/', (req, res) => {
})'/upload',upload.single('image') ,async (req, res) => {
   const { filename: image } = req.file 

   await sharp(req.file.path)
    .jpeg({quality: 50})

    return res.send('SUCCESS!')
app.listen(3333, () => {
    console.log('server on!')
Enter fullscreen mode Exit fullscreen mode

├── upload-config.js

const multer = require('multer')
const path = require('path')

module.exports = {
    storage : new multer.diskStorage({
        destination : path.resolve(__dirname, ".","uploads"),
        filename : function(req, file, callback) {
            callback(null, file.originalname)

Enter fullscreen mode Exit fullscreen mode

conclusion 📣

I am very grateful to be able to share some of the knowledge I have acquired, as teaching is the best way to learn something. Any tips or questions, please contact me via Facebook: Kilmer.
PS: forgive me for something this is my first post
Repository in GitHub :

Top comments (1)

uhn0id profile image

Great example but I think the article could use a 2.0 version where you explain what's going on in the configs/setup so people better understand why certain things are set up how they are. Other than that it's a very useful example!