Image不能是数组或对象



我正在开发一个项目,其中包括发布一个帖子,并能够上传用户图像。我使用JS的前面和NodeJs的后面(Multer上传图像)。我有一个错误,使一个帖子和上传图像到我的DDBB在Mysql。我创建的帖子没有任何错误,但是当我实现发送图像的能力时,我得到了这个错误:

字符串冲突:image不能是数组或对象

代码:

//Here call the action from PostActions
const addPost = (body) => dispatch(createPostAction(body));
const userId = props.credentials?.user.id
//Formate the picture
const formdata = new FormData();
formdata.append('image', image, userId);
const user = post.user;
const token = post.token;
//Create the post
addPost({
title,
content,
image,
userName: post.name,
lastName: post.lastName,
date: new Date(),
userId: user.id,
token: token,
});
//My route
router.post("/", authenticate, fileUpload, async(req, res) => {
try {
const id = req.body;
const image = req.file;
res.json(await postControllers.makePost(id, image))
} catch (error) {
return res.status(500).json({
message: error.message
});
}
});
//My controller
async makePost(post) {
return Post.create(post);
}

我不建议将图像存储在mysql数据库中,或者一般的任何数据库中。

处理图像最常见的方法是将其上传到文件存储系统中,如Amazon S3或Cloudfront,然后将您收到的图像url(通常是图像的文件路径,并且是一个字符串)存储在数据库中。

这是由于性能和带宽的优化。

但是,如果您想将其存储在MySQL数据库中,则需要将其存储为blob。例:

CREATE TABLE 'test'.'pic' (
'pic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'img' LONGBLOB NOT NULL,
PRIMARY KEY ('pic')
)

这个字符串冲突可能是由于MySQL期望一个字符串(图像的路径),并且没有配置为接收blob类型。

要测试,尝试传入一个字符串作为图像键的值,并查看添加帖子是否成功。

最新更新