起初我遇到Multer:意外字段错误,之后我修复直到这里。除图像外,每个板列都保存在DB中。我的邮差测试方法是错的吗?还是我的代码有问题?我如何保存图像url(路径)在板图像列?
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"});
}
});
输入图片描述
输入图片描述
输入图片描述
如果您所说的url
是指为您上传的文件分配的实际路径,则可以在file
对象上使用属性path
。查看所有可用的属性。
你可以这样写:
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
});