'Multer Error: Image url is not save in my Database
At first i met Multer: Unexpected field error, after i fixed until here. every boards column is save in DB except image. is my postman test method is wrong? or my code have problem? how can i save image url(path) in boards image column?
const upload = multer({
storage: multer.diskStorage({
destination(req, file, done) {
done(null, "uploads/");
},
filename(req, file, done) {
const ext = path.extname(file.originalname);
const basename = path.basename(file.originalname, ext);
done(null, basename + new Date().getTime() + ext);
},
}),
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
});
router.post("/images", upload.single("image"), (req, res, next) => {
res.json({ url: `/uploads/${req.file.filename}` });
});
router.post("/", upload.single("image"), async (req, res, next) => {
try {
const {
category,
title,
description,
tags,
latitude,
longitude,
mainAddress,
detailAddress,
} = req.body;
const createBoards = await boards.create({
category,
title,
description,
tags,
latitude,
longitude,
mainAddress,
detailAddress,
image: req.body.url,
});
return res.status(200).json({ data: createBoards, message: "OK" });
} catch (err) {
return res.status(500).json({ message: "Error"});
}
});
Solution 1:[1]
If by url you mean the actual path multer has assigned for your uploaded file, you can use the property path on the file object. See this for all available properties.
So in your case you can do:
const createBoards = await boards.create({
category,
title,
description,
tags,
latitude,
longitude,
mainAddress,
detailAddress,
image: req.file.path // to be safe you should maybe add a check if req.file is defined
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eol |
