Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to Resize Image Before Upload using Multer Sharp in node.js?

create project

File Name :

c:\> npx express --view=ejs mypro

Initialise and Configure Our Project

File Name :

c:\mypro> npm init -y

install

File Name :

Install npm npm install express multer --save npm install sharp --save

create server.js

File Name : server.js

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);

Create Image Upload Form

File Name : index.html

<!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>

Run Application

File Name :

npm start





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here