In this tutorial, you will learn how to resize images before upload using multer, sharp in node js express.
How to Resize Image Before Upload in Node Express JS
Steps to resize the image file before uploading using multer sharp package:
Step 1 – Create Node JS App
In this step, open your cmd and run the following command to create node js app:
mkdir my-app cd my-app npm init -y
Step 2 – Install Express and Multer Dependencies
Run the following command to install express and multer dependencies in your node js application:
npm install express multer --save npm install sharp --save
Step 3 – Create Server.js File
Create server.js
file, and import the above install modules in it:
const express = require('express'); const multer = require('multer'); const path = require('path'); const sharp = require('sharp'); const fs = require('fs'); const app = express(); const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads/'); }, filename: function(req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } }); var upload = multer({ storage: storage }) app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.post('/', upload.single('image'),async (req, res) => { const { filename: image } = req.file; await sharp(req.file.path) .resize(200, 200) .jpeg({ quality: 90 }) .toFile( path.resolve(req.file.destination,'resized',image) ) fs.unlinkSync(req.file.path) res.redirect('/'); }); app.listen(3000);
Step 4 – Create Image Upload Form
Create index.html
file, and create a resized image before uploading the form in it:
<!DOCTYPE html> <html lang="en"> <head> <title>Node js Resize Image Before Upload using Multer Example - Tutsmake .com</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>Node js Resize Image Before Upload using Multer Example - tutsmake.com</h1> <form action="/" enctype="multipart/form-data" method="post"> <input type="file" name="image" accept='image/*'> <input type="submit" value="Upload"> </form> </body> </html>
Click to know more about the express.
Step 5 – Test Application
Run the following command on cmd to start node js express application server:
//run the below command
npm start
Open your browser and type the following URL:
http://127.0.0.1:3000/
Conclusion
In this tutorial, you have learned how to resize or compress image before upload in node js express framework.