4

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

2
  • Did you check what data do you receive client-side? Do you actually receive the base64 string in the response? Commented Mar 27, 2020 at 19:33
  • 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......]} Commented Mar 27, 2020 at 19:36

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.