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

Posted

技术标签:

【中文标题】如何将文件缓冲区转换为 <img> 标签 src?【英文标题】:How to convert a file buffer to <img> tag src? 【发布时间】: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 【参考方案1】:

像这样转换成base64string

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

【讨论】:

【参考方案2】:

将 dataUrl 保存为字段类型为 mediumtext 的数据库中的字符串,并在检索集源时如下所示:

src='$data[i].data_url ? data[i].data_url : '''

它对我有用。

【讨论】:

以上是关于如何将文件缓冲区转换为 <img> 标签 src?的主要内容,如果未能解决你的问题,请参考以下文章

如何将图片转换成html

如何将 bytearray 转换为 img 标签?

如何:将 boost::endian 缓冲区类型转换回本机格式

如何将数组组转换为 Json?

如何使用 php 将 .docx、xslx、img、txt 等任何文件转换为 PDF 预览?

如何将 URL 从 Webapi 传递到 <img> 标签以接受 base64 的图像?