3

I tried to resize my image when it's being uploaded, but I am not succeeding. I am using Node, Expressjs, Mongoose, Multer and Sharp. How do I resize it on upload with Sharp.

Here is my create routes

router.post('/create', upload.single('cover'), async (req, res, next) => {
 const fileName = req.file != null ? req.file.filename : null
 let witdth = 100;
 let height = 100;

 sharp(req.file)
 .resize(witdth, height).toFile(req.file.path)


 const event = new Event({
 startingDate: req.body.startingDate,
 closingDate: req.body.closingDate,
 title: req.body.title,
 description: req.body.description,
 eventImage: fileName 
})
try {    
  const events = await event.save()
  res.redirect("/events")

  } catch {
   if (event.eventImage != null) {
     removeeventImage(event.eventImage)
   }
    res.render("events/new")
 }
});

and my uploader path

const uploadPath = path.join('public', Event.eventImageBasePath)
const imageMineTypes = ['image/jpeg', 'image/png', 'image/gif']

const upload = multer({ 
  dest: uploadPath,
  fileFilter:  (req, file, callback) => {
  callback(null, imageMineTypes.includes(file.mimetype) )
 }
})

and this is the error that it's giving

(node:7447) UnhandledPromiseRejectionWarning: Error: Input file is 
  missing

What am I doing wrong here?

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

3

If you specify dest option in multer() it will save the file to that directory and you will have to pass that directory to sharp() like this

sharp(req.file.path)

Otherwise you can drop the dest option and pass the buffer to sharp()

sharp(req.file.buffer)

...

 multer({ 
  fileFilter:  (req, file, callback) => {
  callback(null, imageMineTypes.includes(file.mimetype) )
 }
thammada.ts
  • 5,065
  • 2
  • 22
  • 33