Reputation: 129
I have the following code on an express server, to read an image and send it to the client via api
router.get("/file",async (req,res)=>{
const objImg = {img:null}
const result = await SELECT("...");
if(result.length>0){
var bitMap= fs.readFileSync(`./src/logosClient/${result.nombImg}`)
objImg.img=new Buffer.from(bitMap,"base64")
}
res.json(objImg)
})
The api data arrives as follows
data:{type: "Buffer", data: [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 192, 0, 0, 0, 46, 8, 6......]}
In my ReactJs client, I have the following code to receive it
import React, {useEffect, useState} from 'react';
import muestra from '../../../../resources/images/muestra.png'
const Index = () => {
const [previewImg, setPreviewImg] = useState(null)
useEffect(()=>{
RunApi("/generales/file","GET",null,null).then(result=>{
if(result.img){
setPreviewImg("data:image/png;base64," + result.img.data)
}
}).catch(error=>{
addToast("error","Error",error)
})
},[])
return(
<img src={previewImg?previewImg:muestra} className="align-self-center mr-3" alt="..."/>
)
}
I can't see the image but it doesn't generate any error message either
Upvotes: 3
Views: 10585
Reputation: 1125
Try to convert your image to base64 string like
objImg.img = new Buffer.from(bitMap).toString("base64")
And then set your state like
setPreviewImg("data:image/png;base64," + result.img)
Upvotes: 8