When a user updates their profile image I want to delete the old one and update the image name in the database. The newly uploaded image is uploaded using react filepond and kept being deleted as well whenever a new image was uploaded. Upon investigating, I found that the request was being sent twice so it was deleting the file after it was uploaded. After I removed the last line of code it stopped doing that and worked fine. But why?
Controller:
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/img");
},
filename: (req, file, cb) => {
const ext = file.mimetype.split("/")[1];
cb(null, `hero-${Date.now()}.${ext}`);
}
});
// test if uploaded file is an image
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
// throw error here
cb(console.log("not an image"), false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter
});
exports.uploadUserPhoto = upload.single("bgImg");
exports.updateHeroImg = async (req, res) => {
const updateId = "5d13b3c6dd57c43828ed5a7a";
const hero = await Hero.findById(updateId);
if (!hero) return;
const oldImg = hero.bgImg;
fileHelper.deleteFile("public/img/" + oldImg);
if (req.file) hero.bgImg = req.file.filename;
const result = await hero.save();
res.status(200).send("image uploaded");
};
As soon as I remove this line it works fine. Any ideas?
res.status(200).send("image uploaded");
This is the route:
router.post("/", heroController.uploadUserPhoto, heroController.updateHeroImg);
In React I have:
<FilePond
ref={ref => (this.pond = ref)}
files={this.state.files}
allowMultiple={false}
maxFiles={1}
instantUpload={false}
maxFileSize={5000000}
name="bgImg"
server={{
process: "http://localhost:8000/api/hero/",
load: "http://localhost:8000/img/"
}}
oninit={() => this.handleInit()}
onupdatefiles={fileItems => {
// Set currently active file objects to this.state
this.setState({
files: fileItems.map(fileItem => fileItem.file)
});
}}
//onprocessfile={() => this.uploadComplete()}
/>
uploadComplete = () => {
putImg(this.state.files);
toast.success("Image successfully updated");
};