DEV Community

Cover image for Simple Node JS Resize Image Before Upload using Sharp Multer
Ranjan Singh
Ranjan Singh

Posted on • Edited on

Simple Node JS Resize Image Before Upload using Sharp Multer

Motivation :

Every time we upload an image to NodeJS server there are a lot of possibility we also need to optimise or resize the image or both that's why I made a simple package to handle both of the operations at same time called sharp-multer.

Introduction :

Multer : Multer is a Express.js middleware which is used for handling multipart/form-data, which is mostly used library for uploading files.
Sharp : Sharp high is a speed Node.js module is to convert large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.

Sharp-Multer : Node js Utilty package to use with Multer as storage engine to optimise images on the fly using Sharp.

Installation & Configuration:

1. Create Node JS App

mkdir test-app
cd test-app
npm init
Enter fullscreen mode Exit fullscreen mode

2. Install Modules

npm install express multer --save
npm install sharp --save
npm install sharp-multer --save
Enter fullscreen mode Exit fullscreen mode

3. Create Server.js File and Import Modules

const express = require("express")
const path = require("path")
const multer = require("multer")
const SharpMulter  =  require("sharp-multer");
const app = express()
Enter fullscreen mode Exit fullscreen mode

4. Setup Sharp Multer to handle Images
Here we are creating a storage engine for Multer.
destination : you can return any directory you want to store the image make sure the directory is created.
imageOptions : we can pass the size height, width for resizing as well as quality and fileformate (jpg,wep,png) to convert the incoming image for optimisation.

const storage =  
 SharpMulter ({
              destination:(req, file, callback) =>callback(null, "images"),
              imageOptions:{
               fileFormat: "jpg",
               quality: 80,
               resize: { width: 500, height: 500 },
                 }
           });
const upload  =  multer({ storage });
Enter fullscreen mode Exit fullscreen mode

5. Create Route with Multer Middleware

app.post("/upload", upload.single("avatar"), async  (req, res)  => {
console.log(req.file);
return  res.json("File Uploaded Successfully!");
}


Enter fullscreen mode Exit fullscreen mode

6. Add HTML file to render the Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>File Upload</title>
</head>
<body>
    <div class="container">
        <h1>File Upload</h1>
<!--Create a form to send the file to a route  "upload"-->
<!--Set the request method to POST-->
<!--Set the encytype to "multipart/form-data" in order to send files and not just text-->
        <form action="/upload" method="POST" enctype="multipart/form-data">
            <div class="file-field input-field">
              <div class="btn grey">
                <input type="file" name="avatar">
              </div>
            </div>
            <button class="btn" type="submit">Submit</button>
          </form>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

7. Serving File and defining Port

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});


app.listen(3000, () => {
  console.log(`Server is running on port ${3000}`)
})
Enter fullscreen mode Exit fullscreen mode

8. Running the Server

node Server
Enter fullscreen mode Exit fullscreen mode

After that you can open your browser and start uploading the images will be automatically optimised and stored in the destination you defined on setting up sharp multer.

For more advance options and watermark check out next part

Thanks for reading try it out once 😃

Top comments (0)