Table of Content
Resize Image upload using multer & sharp in node js
Last modified: May 09, 2022- Create a util file called imageUpload
- install i sharp
- create uploads folder
const sharp = require('sharp');
const imageUpload = async (req) => {
const formattedFileName = req.file.originalname.split(' ').join('-'); //replace space with -
try {
await sharp(req.file.buffer)
.resize({with:800, height:600}) //max width = 800 or height = 600
.toFile('./uploads/'+ formattedFileName); //upload to /upload folder
} catch (error) {
console.log(error);
}
}
module.exports = imageUpload;
- create image.controller
- install i multer
const multer = require('multer');
const storage = multer.memoryStorage();
const uploadFile = multer({storage});
const imageUpload = require('../util/imageUpload.util')
module.exports = function(app) {
app.post("/api/image/upload" , uploadFile.single('uploadfile'), async function(request, response){
await imageUpload(request);
});
}
- finally register the controller
require('./controllers/image.controller')(app);