Home > Back-end >  I can't get my image to be updated with the new one in node js express file uploader, I couldn&
I can't get my image to be updated with the new one in node js express file uploader, I couldn&

Time:01-10

I'm trying to update my post and everything is working except the image, when I update the image src is becoming UNKNOWN, this is my code:

exports.updatePost = async (req, res) => {
  try {
    const post = await Post.findOne({ slug: req.params.slug });
    let uploadeImage = req.files.image;
    let uploadPath = __dirname   "/../public/uploads/"   uploadeImage.name;
    uploadeImage.mv(uploadPath, async () => {
      post.image = "/uploads/"   uploadeImage.name;
      post.title = req.body.title;
      post.desc = req.body.desc;
      post.image = req.body.uploadeImage;
      post.save();
      res.status(200).redirect("/posts");
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      error,
    });
  }
};

CodePudding user response:

It's better to use multer as a middleware in front of your route to upload files then in your route you have access to req.file ,store reference in db as:

post.image= req.file.filename // or full path
  •  Tags:  
  • Related