Send image from form-data and JSON data from postman for node js

Viewed 1172

Problem

How I received the image and JSON data from the postman in node js API? When I send the image from form-data and also send the JSON data only one received. If the image is shown in the request then JSON data not received and validation error occurred.

How I handle this case? Make separate API for image upload. What is the best way todo this

account.js

const express = require('express');
const multer = require('multer');
const { constants } = require('../helpers/contants');
const { commonValidation } = require('../validation/commonValidation');

const { validation } = require('../middleware/validation');
const crypto = require("crypto");

const {
updateProfile,

} = require('../controllers/account');


 
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, `public/${constants.imageDir}`)
},
filename: async (req, file, callback) => {
var filetype = '';
  if(file.mimetype === 'image/jpg') {
    filetype = 'gif';
  }
  if(file.mimetype === 'image/png') {
    filetype = 'png';
  }
  if(file.mimetype === 'image/jpeg') {
    filetype = 'jpg';
  }
  callback(null, 'image-' + crypto.randomBytes(3).toString('hex') + '-' + 
  Date.now() + '.' + filetype);
  
 }

 })
 var upload = multer({ storage: storage,fileFilter: (req, file, callback) => {
 if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || 
 file.mimetype == "image/jpeg") {
 callback(null, true);
 } else {
  callback(null, false);
 return callback(new Error('Only .png, .jpg and .jpeg format allowed!'));
 }
 } });



 const router = express.Router({ mergeParams: true });

 router.use(upload.single('image'));
 router.use((req, res, next) => {
  if (!Array.isArray(req.image)) {
  req.image = []
 } 
  req.body = req.body.request 
  if (req.file) {
   //set the avatar in req to get the image name in updateProfile controller
  req.body.avatar = req.file.filename;
  req.image.push(req.file.filename)
  }

  return next()
  })
  router
  .patch('/', [commonValidation('updateProfile')], validation, updateProfile)


   module.exports = router;

commonValidation

 exports.commonValidation = (method) => {
 switch (method) {

 case 'updateProfile': {
 return [
    check('name', 'Name is required').not().isEmpty().trim().escape(),
    
  ]
}
}

validation

const { validationResult } = require('express-validator');


module.exports.validation = (req, res, next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
return next() 
}
// err.message = 'ValidationError';

const extractedErrors = []
errors.array({ onlyFirstError: true }).map((err) => extractedErrors.push({ 
[err.param]: err.msg }))
next(extractedErrors);

}

account

  exports.updateProfile = asyncHandler(async (req, res, next) => {




 if(typeof req.body.avatar !== 'undefined'){
 const oldImage = await User.findById(req.user._id);

 //oldImage.avatar exist then delete the previous image from directory
 if(oldImage.avatar){

  deleteImageFromFolder('images',oldImage.avatar)
 
  }
  }
 const user = await User.findByIdAndUpdate(req.user._id, req.body, {
 new: true,
 runValidators: true
 });

 const profile = user.getProfile();


 res.status(200).json({
   success: true,
   data: profile
   });
   });

postman

In this below image JSON data and image received but the validation error occurs

Debugger

I also used this approach but still got validation error

Postman headers

0 Answers
Related