Monday, 2 September 2019

doing post, put and get in one request in express

Hello, I want to do a request on my express server that should to the following things:receive a base64 code, convert it to an image and safe the image on the serverreceive a userId, find this user in mongoDb, get the old imageUrl and delete this image from serverreceive a userId, find this user in mongoDb and update the url to the new image​Now actually I have the following post request to upload the image:router.post('/change-profile-image/:id', verifyToken, (req, res) => { var id = req.params.id; let userData = req.body; var str = userData.image; var base64StringSplit = str.split(',', 2); var base64String = base64StringSplit[1]; fs.writeFile('./uploads/user/'+ id + '/profileimage_' +userData.name, base64String, {encoding: 'base64'}, (err) => { if(err) console.log(err); else console.log("file created") }) }); additionally I have a put request to update the db url:router.put('/change-profile-image-in-db/:id', verifyToken, (req, res) => { var id = req.params.id; let userData = req.body; let dbPath = "http://localhost:3000/user/" + id + "/profileimage_" + userData.name; User.updateOne({_id: id}, {$set: {"profileImage": dbPath}}, (error, result) => { if(error) console.error(error); else { res.status(200).send(result); } }); }); Now I still need something like this:let user = User.findOne({_id: id}, {password: 0}, (err, result) => { if(err) console.log(err); }) //userprofile looks like this: http://localhost:3000/user/5d6b7f5c2f1a7036d0e1c360/profileimage_IMG_5143.JPG var url = user.userprofile.split('/', 6); var img = url[5]; fs.unlinkSync(img, (err) => { if(err) console.log(err); }) IS there a possibility to put all this snippets of code in one request or at least add the last one to one of the first?

Submitted September 02, 2019 at 10:59AM by UnknownInnocent

No comments:

Post a Comment