如何将文件缓冲区转换为 <img> 标签 src?

hin*_*991 4 buffer mongoose mongodb node.js reactjs

我正在开发一个应用程序,使用 Node.js 作为后端,并作为我的前端进行反应。现在我创建了一个上传文件并将其作为缓冲区类型存储在 mongodb 中的路由。我的问题是,当我在 React 应用程序中收到这些数据时,如何使用这些数据将其转换为 html 图像标签中的源属性?当我查看 mongodb 指南针时,文件属性如下所示:(非常长的字符串)

在此输入图像描述 当我查看对象本身时,当我得到它作为响应时,它看起来像这样:(数字数组); 在此输入图像描述

我尝试使用

  <img
      src={`data:${props.images[0].mimetype};base64,${props.images[0].file.data}`}
    />
Run Code Online (Sandbox Code Playgroud)

但它没有用..

在此输入图像描述

如果有人能给出答案,真的很感激!

猫鼬模型:

   images: [
    {
    file: { type: Buffer },
     filename: { type: String },
    mimetype: { type: String }
   }
  ]
Run Code Online (Sandbox Code Playgroud)

节点.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 });
....
Run Code Online (Sandbox Code Playgroud)

Jas*_*les 9

像这样将其转换为 base64string

  <img
      src={`data:${props.images[0].mimetype};base64,${Buffer.from(props.images[0].file.data).toString('base64')}`}
    />

Run Code Online (Sandbox Code Playgroud)