2

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>
        );
1
  • you can't modify the backend to return the buffer as a base64 string? Commented Nov 23, 2021 at 7:20

1 Answer 1

3

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

2 Comments

Thank you this worked the only edit I needed was setUserProfileImage(data:${user.userPhotoExtensionType};base64, ${Buffer.from( user.userPhoto.data).toString('base64')} );
Glad i could help. I actually thought about the Buffer.from but wasn't sure. It's good you figured it out.

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.