如何将NodeJS Buffer格式图片转Base64在前端img标签显示?
解决方案
方案一:后端提前返回Base64编码(推荐)
在后端将Buffer转换为Base64字符串后再返回,前端直接拼接使用即可,避免前端额外转换:
router.get("/get-reviews", async (req, res) => { const review = await Review.find(); const imgInfo = review[0].img; // 将Buffer数据转为Base64字符串 const base64Str = imgInfo.data.toString('base64'); res.json({ test_img: { contentType: imgInfo.contentType, base64: base64Str } }); });
对应前端代码:
async function displayTestImg() { const { test_img } = await fetch("/get-reviews").then(res => res.json()); document.getElementById("my_container_element").innerHTML = ` <img src="data:${test_img.contentType};base64,${test_img.base64}" alt="评论图片"> `; } displayTestImg();
方案二:前端处理数组转Base64
前端接收到的test_img.data.data是数字数组,需要先转为Uint8Array,再编码为Base64:
async function displayTestImg() { const { test_img } = await fetch("/get-reviews").then(res => res.json()); // 将数字数组转为Uint8Array const uint8Arr = new Uint8Array(test_img.data.data); // 逐字节转为ASCII字符后用btoa编码 const base64Str = btoa(String.fromCharCode(...uint8Arr)); document.getElementById("my_container_element").innerHTML = ` <img src="data:${test_img.contentType};base64,${base64Str}" alt="评论图片"> `; } displayTestImg();
如果你的前端环境支持Buffer(如Webpack/Browserify打包项目、现代浏览器),可以简化为:
async function displayTestImg() { const { test_img } = await fetch("/get-reviews").then(res => res.json()); const base64Str = Buffer.from(test_img.data.data).toString('base64'); document.getElementById("my_container_element").innerHTML = ` <img src="data:${test_img.contentType};base64,${base64Str}" alt="评论图片"> `; } displayTestImg();
内容的提问来源于stack exchange,提问作者Oscar
相关产品推荐
相关产品推荐

