当用户更新他们的个人资料图片时,我想删除旧的并更新数据库中的图片名称。新上传的图像是使用 react filepond 上传的,并且每当上传新图像时也会被删除。经过调查,我发现请求被发送了两次,所以它在上传后删除了文件。在我删除最后一行代码后,它停止这样做并且工作正常。但为什么?
控制器:
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");
};
一旦我删除这条线,它就可以正常工作。有任何想法吗?
res.status(200).send("image uploaded");
这是路线:
router.post("/", heroController.uploadUserPhoto, heroController.updateHeroImg);
在反应我有:
<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");
};