且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Node.js检索Mongodb中存储的图像

更新时间:2023-08-19 23:23:46

因此,您看起来像在数据库中保存了base64映像.

So looks like you save a base64 image in your db.

您可以这样执行 img:Buffer(encImg).在node.js中,默认的Buffer编码为 utf8 ,因此您的映像将以MongoDB中二进制类型的base64 utf8字符串形式保存在db中!

You do this like this img: Buffer(encImg). In node.js default Buffer encoding is utf8, so your image is saved in db as a base64 utf8 string under binary type in MongoDB!

一种正确的方法是在保存图像时指定缓冲区编码:

A proper way will be to specify a buffer encoding when you save your image:

// ...
img: Buffer.from(encImg, 'base64')
// ...

这样,当您将响应作为 res.send(results.img.buffer); 发送给客户端时,您将发送二进制数据而不是base64字符串.

That way when you send a response to client as res.send(results.img.buffer); you'll send binary data instead of a base64 string.