我正在尝试检索以Buffer格式存储在数据库中的图像,并将其显示为真实图像。我知道这是可能的,而且我有最后解释的正确数据。
后端NodeJS&Express(mongodb数据库(:
router.get("/get-reviews", async (req, res) => {
const review = await Review.find() // Getting all my reviews from my database.
console.log(review[0].img); // Below is my img object where you can see it is in a Buffer format of some sort.
/*
img: {
data: new Binary(Buffer.from("52494646e42300005745425056503820d8230000d018019d012a...", "hex"), 0),
contentType: 'image/webp'
}
*/
res.json({ test_img: review[0].img });
});
前端Javascript:
async function displayTestImg() {
const data = await fetch("/get-reviews").then(res => res.json())
console.log(data); // Below is what I am retriving from my server, still some buffer format but looks a little different for some reason
/*
contentType: "image/webp"
data:
data: (9196) [82, 73, 70, 70, 228, 35, 0, 0, 87, 69, 66, 80, 86, 80, 56, 32, …]
type: "Buffer"
*/
document.getElementById("my_container_element").innerHTML = `
<img src="data:${ test_img.contentType };base64,${ test_img.data.toString('base64') }">
`;
// Here I am getting the error: GET data:image/webp;base64,[object Object] net::ERR_INVALID_URL
document.getElementById("my_container_element").innerHTML = `
<img src="data:${ test_img.contentType };base64,${ test_img.data.data.toString('base64') }">
`;
// Here I am getting the error: GET data:image/webp;base64,82,73,70,70,228,35,0,0,87,69,66,80,86... net::ERR_INVALID_URL
} displayTestImg();
正如你所看到的,我尝试过的两件事都给了我错误。这是令人困惑的,因为当我通过res.render("index", { test_img: reviews[0].img });
发送数据并通过EJS加载数据时,就像这样:<img src="data:<%= review.img.contentType %>;base64,<%= review.img.data.toString('base64') %>" alt="">
,那么它工作得非常好!然而,我需要通过JavaScript加载它,那么我该如何实现呢?
好的,所以我终于找到了答案:
Buffer对象只存在于NodejS中,所以当我尝试在它上使用.toString('base64')
时,它只将实际对象作为字符串返回,而不是转换它
我发现的解决方案是这个功能:
function toBase64(arr) {
return window.btoa(arr.reduce((data, byte) => data + String.fromCharCode(byte), ''));
}
所以我所要做的就是输入以下内容,它起到了作用!
document.getElementById("my_container_element").innerHTML = `
<img src="data:${ test_img.contentType };base64,${ toBase64(test_img.data.data) }">
`;