What I am trying to do is delete the images with same id before I upload a new image, if the user has inputed image. Multer does not provide a way to detect if there is an input only, it has to upload the file first.
So I figured out to use another form-data libarary to do just that. But when I do that multer doesn't recieve the form-data to upload. So it doesn't upload anything. The image only get delete, but no new images are added.
The problem is I can't parse for data twice. How can i fix it? Or is there a workaround?
Code explination
I am using multyparty to detect if the user has included an image in a form.
form.parse(req, async (err, fields, files) => {
if (err) console.log(err);
else if (files.image) removeImagesWithSameId(req.params.id)
});
If there an image in the form then delete the previous uploaded image
const removeImagesWithSameId = (id) => {
fs.unlink(__dirname + id + ".jpg", (err) => {
if (err) console.log(err)
console.log("image Delete")
})
}
Then upload the new image, using multer.
upload(req, res, (err) => {
if (err) console.log(err)
else if (req.file) console.log("Image uploaded")
});
Execpt the new image not getting uploaded, because multer not receiving the data and req.file
is undefined.
My questions is why multer is not receiving the data when ever I add multiparty, and how to fix it?
Whole the code
const express = require('express');
const app = express();
const multiparty = require('multiparty');
const form = new multiparty.Form();
var upload = multer({ dest: __dirname }).single('image');
const removeImagesWithSameId = (id) => {
fs.unlink(__dirname + id + ".jpg", (err) => {
if (err) console.log(err)
console.log("image Delete");
})
}
app.post('/upload/:id', (req, res) => {
form.parse(req, async (err, fields, files) => {
if (err) console.log(err);
else if (files.image) removeImagesWithSameId(req.params.id)
});
upload(req, res, (err) => {
if (err) console.log(err)
else if (req.file) console.log("Image uploaded")
});
})
Note this is only demonstration of the probelm. My actaul code is bit longer then that.
For people who is asking about the requst, I am using nodemon, but this equivalent curl requst.
curl --location --request PUT 'localhost/upload/1593735936343' \
--form 'image=@/C:/Users/Hamza/images/test.jpg'