【发布时间】:2020-01-02 02:35:11
【问题描述】:
我正在开发一个应用程序,使用 Node.js 作为后端并作为前端做出反应。 现在我创建了一个上传文件并将其作为缓冲区类型存储在 mongodb 中的路由。 我的问题是,当我在我的反应应用程序中收到这些数据以将其转换为 html 图像标签中的源道具时,我该如何使用它? 当我查看 mongodb 指南针时,文件属性如下所示:(非常长的字符串)
当我看到对象本身时,当我得到它作为响应时,它看起来像这样:(数字数组);
我尝试使用
<img
src={`data:${props.images[0].mimetype};base64,${props.images[0].file.data}`}
/>
但它没有工作..
如果有人能给出答案,我真的很感激!
猫鼬模型:
images: [
{
file: { type: Buffer },
filename: { type: String },
mimetype: { type: String }
}
]
node.js
var multer = require('multer');
var upload = multer({
limits: {
fileSize: 1000000
}
});
app.post('/upload', upload.single('file'), async (req, res) => {
try {
const file = {
file: req.file.buffer,
filename: req.file.originalname,
mimetype: req.file.mimetype
};
// console.log(req.file.buffer.toString('base64'));
const product = new Product({ ...req.body });
product.images = [file];
await product.save();
res.status(201).send({ success: true, product });
...
app.get('/api/products/:id', async (req, res) => {
try {
const product = await Product.findById({ _id: req.params.id }).populate(
'brand'
);
if (!product) {
throw new Error('Cannot find the requested product');
}
res.send({ product });
....
【问题讨论】:
-
有点跑题了,但我可以建议您将图像存储在 ms azure 或 aws s3 之类的云存储上,并且只将 url 存储在数据库中吗?我想这可能会为您省去这些麻烦和其他麻烦。
-
我也可以将它保存在节点 js 的文件夹中,但我希望每个图像都存在于它所属的对象中(即产品模型),这样我就可以轻松找到每个产品图像..
-
我知道了,只是建议将图像保存到云端,产品型号中有
images: [{url: String}],但这只是一个建议。 -
这可能是一个解决方案,但我仍然想知道如何让这些东西发挥作用..
-
那一长串数字可能是ArrayBuffer(或者你需要create one from it)。然后convert it to base64
标签: node.js reactjs mongodb mongoose buffer