Ravindra S. Patil
Ravindra S. Patil

Reputation: 14785

Upload Image and PDF in rest API using node js with mongoose

I have try to insert some data into mongodb database using node js REST API but I got an error Unexpected field Im new to node please help me. whitePaper is my pdf file If I upload data like title, description and image only it gives the Correct answer with status code 201 but I try to upload all data and pdf but it gives the error

model code:

    description: {
      type: String,
      required: true
    },
    imgURL: {
      type: String,
      required: true
   },
   whitePaperLink: {
      type: String,
      required: true,
                
   },

app.js file

app.use('/whitePaper', express.static('whitePaper'));

router file

const whitePaperLink = multer.diskStorage({
 destination: './whitePaper/',
 filename: (req, file, cb) => {
      return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
 }
});
const whitePaperFilter = (req, file, cb) => {
 if (file.mimetype === 'application/pdf') {
      cb(null, true)
 } else {
      cb(null, false)
 }
};
const whitePaperUpload = multer({
 storage: whitePaperLink,
 limits: {
      fileSize: 1024 * 1024 * 5
 },
 fileFilter: whitePaperFilter
 });

router.post('/', checkAuth, imageUpload.single('imgURL'), whitePaperUpload.single('whitePaperLink'), 
PostController.create_Post)

controller file

exports.create_Post = async (req, res) => {
 const post = new Post({
      title: req.body.title,
      category: req.body.category,
      description: req.body.description,
      imgURL: req.file.path,
      whitePaperLink: req.file.path,
      publishDate: req.body.publishDate,
 });

 try {
      const addPost = await post.save()
      res.status(201).json({
           message: 'Post Added Succesfully.'
      })
 } catch (error) {
      console.log(error);
      res.status(500).json({
           message: error
      })

 }
}

Upvotes: 0

Views: 1256

Answers (1)

Abhishek Pankar
Abhishek Pankar

Reputation: 743

If you'll use upload.single for each field it'll give error Unexpected Field.

Multer takes all files at once for execution, and in your case you've 2 different files and it'll take both files to upload.single.

So, instead of upload.single use upload.fields.

In your route.js, do it like this:

const destination = (req, file, cb) => {
     switch (file.mimetype) {
          case 'image/jpeg':
               cb(null, './images/');
               break;
          case 'image/png':
               cb(null, './images/');
               break;
          case 'application/pdf':
               cb(null, './whitePaper/');
               break;
          default:
               cb('invalid file');
               break;
     }
}

const storage = multer.diskStorage({
     destination: destination,
     filename: (req, file, cb) => {
          return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
     }
});

const fileFilter = (req, file, cb) => {
     if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'application/pdf') {
          cb(null, true)
     } else {
          cb(null, false)
     }
};

const upload = multer({
     storage: storage,
     limits: {
          fileSize: 1024 * 1024 * 5,
     },
     fileFilter: fileFilter
});

// add post
router.post('/', upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }]), PostController.create_Post)

Edit:

You can also do it like this:

const uploadPostData = (req, res, next) => {
     upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }])(req, res, (err) => {
          console.log(req.files);
          req.body.imgURL = req.files.imgURL[0].path.replace('/\\/g','/');
          req.body.whitePaperLink = req.files.whitePaperLink[0].path.replace('/\\/g','/');
          next()
     })
}

// add post
router.post('/', uploadPostData, PostController.create_Post)

Upvotes: 1

Related Questions