node.js - Node.js、multer、express、sequelize、Postgres
问题描述
我目前正在尝试将图像存储在我的数据库中。
这是我的帖子模型:-
id: {
field: "PostId",
type: Sequelize.INTEGER,
primaryKey: true,
},
title: {
type: Sequelize.STRING,
},
images: {
type: Sequelize.STRING
}
这是我的发帖请求:-
router.post(
"/",
[
upload.array("images", config.get("maxImageCount")),
imageResize,
],
async (req, res) => {
const paths = await req.files.map((file) => ({ fileName: file.filename }));
Posts.create({
title: req.body.title,
images: JSON.stringify(paths),
}).then(
() => {
res.status(201).send({
msg: "upload successful",
});
},
(validation) => {
res.status(422).json({
errors: validation.errors.map((error) => {
return {
fieldName: error.path,
message: error.message,
};
}),
});});});
我现在正在使用 multer 将我的图像存储在磁盘上,并使用锐利来调整我的图像大小。
我的问题是当我去 localhost/posts 时,图像是这样的:-
`"images":"[{\"fileName\":\"95aa17.png-2020-11-08T14:24:33.221Z\"},{\"fileName\":\"fwfe.png-2020-11-08T14:24:33.268Z\"}]"`
当它应该看起来像这样时:-
`"images":"[{"fileName":"95aa17.png-2020-11-08T14:24:33.221Z"},{"fileName":"fwfe.png-2020-11-08T14:24:33.268Z"}]"`
经过数小时的研究,我发现为了最佳实践,我不应该在数组上使用 JSON.stringify。
我应该如何解决这个问题?
解决方案
我设法解决了这个问题。这是解决方案:
router.post(
"/",
[
upload.array("images", config.get("maxImageCount")),
imageResize,
],
async (req, res) => {
const paths = await req.files.map((file) => ({ fileName: file.filename }));
Posts.create({
title: req.body.title,
images: paths.map((x) => ({ images: x.fileName }));
}).then(
() => {
res.status(201).send({
msg: "upload successful",
});
},
(validation) => {
res.status(422).json({
errors: validation.errors.map((error) => {
return {
fieldName: error.path,
message: error.message,
};
}),
});});});
我将图像作为文件名存储在数据库中。
推荐阅读
- php - 不允许的方法 - Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException 不支持 POST 方法
- sql - Sqliteman 中的别名问题试图制作唯一的 id
- docker - Docker 无法启动,因为我没有足够的内存。如何解决?
- firebase - 无法在 Cloud Functions for Firebase 中引用环境变量
- mysql - 我的评论代码有什么问题?
- python-3.x - 如何在python中显示二进制图像数据?
- html - 尝试水平对齐 5 张图像。一张图片脱节了
- scala - 为什么我的代码无法识别上面声明的函数?
- gojs - gojs addNodeData 函数不会将节点添加到图表
- c++ - 在 C++ 中,是否可以定义一个具有不同代码块的函数,以通过另一个函数执行和传递?