Can't get the correct file upload using multer and node

Viewed 39

I'm making a post request to create a "employee" filling some formData, and in this form there's a field for an image upload, the problem is that no matter what image I choose I always get the default image from the response, but the filename is being saved correctly in my local directory.

employeeRoute.js:

router
    .route('/employee')
    .get(employeeController.getAllEmployee)
    .post(
    authController.protect,
    authController.restrictTo('admin'),
    employeeController.uploadEmployeephoto,
    employeeController.resizeEmployeePhoto,
    employeeController.createEmployee
    );

employeeController.js:

const multerStorage = multer.memoryStorage();

const multerFilter = (req, file, cb) => {
  if(file.mimetype.startsWith('image')){
    cb(null, true)
  } else {
    cb(new AppError('Not an image!', 400), false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter
});

exports.uploadEmployeephoto = upload.single('photo');

exports.resizeEmployeePhoto = (req, res, next) => {
  if(!req.file) return next();

  req.file.filename = `employee-photo-${Date.now()}.jpeg`;

  sharp(req.file.buffer)
  .resize(512,512)
  .toFormat('jpeg')
  .jpeg({quality:90})
  .toFile(`public/images/our-experts/${req.file.filename}`);

  next();
}
exports.createEmployee = factory.createOne(Employee);

factory

exports.createOne = Model =>
  catchAsync(async (req, res, next) => {
    console.log(req.file);

    const doc = await Model.create({
      ...req.body,
      path: req.file.path
    });
    res.status(201).json({
      status: 'success',
      data: {
        data: doc
      }
    });
    console.log(req.body);
  });

enter image description here

1 Answers

It was a simple mistake, I was just forgetting to pass

req.body.photo = req.file.filename

exports.createOne = Model =>
  catchAsync(async (req, res, next) => {
    if(req.file) req.body.photo = req.file.filename;

    const doc = await Model.create(req.body);
    res.status(201).json({
      status: 'success',
      data: {
        data: doc
      }
    });
    console.log(req.body);
  });
Related