Home > Blockchain >  How to convert MongoDB Buffer to Image in React/Node/Express
How to convert MongoDB Buffer to Image in React/Node/Express

Time:11-23

Technical Specifications: React, Node, Express, MongoDB through Mongoose

I am building my GET API to retrieve user images from my MongoDB. I Currently have my document containing the image value as a buffer(see screenshot #1)enter image description here

The GET API returns the following data(see screenshot #2): enter image description here

The Question I have is how do convert the Buffer value returned from MongoDB into a variable type that can be used to display the image representation of the Buffer.

I found some answers online such as the following code but I do not fully understand how the values are parsed. Source: https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/

<img src="data:userPhoto/<%=image.img.contentType%>;base64,
   <%=userPhoto.img.data.toString('base64')%>"/>
   

I would ideally like to use extract the Buffer value from the API response and then convert directly to an image and then pass that image to the html/react component. Similar to the following code below:

const [userProfileImage, setUserProfileImage] = useState({});
//in API GET call
await axios({
        method: 'get',
        url,
    }).then(function(response){
       setUserProfileData(response.data[0].userPhoto.data);
    }



   //code to convert the local userProfileImage Buffer value to   image, using Node Base64 maybe ??
   //Not too sure what variable types I should pass into the Buffer.from
    let imageValueConverted = Buffer.from(userProfileImage, '').toString('');
    return (
            <div>
                <img src={imageValueConverted}/>
            </div>
        );

CodePudding user response:

Try to set the image like so:

const [userProfileImage, setUserProfileImage] = useState({});
//in API GET call
axios({
    method: 'get',
    url,
}).then(function(response){
    let user = response.data[0];
    setUserProfileImage(`data:${user.userPhotoExtensionType};base64, ${Buffer.from(user.userPhoto.data).toString('base64')}`);
});

and render it like this:

return (
    <div>
        <img src={userProfileImage}/>
    </div>
);
  • Related