skip to Main Content

in mongodb my image is saved as
image: BinData(0, 'QzpcZmFrZXBhdGhcV2hhdHNBcHAgSW1hZ2UgMjAyMi0xMi0wNCB40Ny4zMS5qcGc=')

I am trying to access this image in my frontend Reactjs like this

{userData.image ? <img src={data:image;base64,${userData.image}} alt="User profile image" width="200" height="200" /> : <img src={'./Images/profile.png'} alt="Default image" width="200" height="200" /> }

but it is not showing this image

How can i access this decode this image back to its original form

2

Answers


  1. This is how you can display the images in your React component:

    import React, { useState, useEffect } from 'react';
    
    function User() {
      const [userData, setUserData] = useState([]);
    
      useEffect(() => {
        async function fetchUsers() {
          try {
            const response = await axios.get('/api/users');
            setUserData(response.data);
          } catch (error) {
            console.error(error);
          }
        }
    
        fetchUsers();
      }, []);
    
      return (
        <div>
          {users.map(user => (
            <div key={userData._id}>
              {/* Display the user's image */}
              <img
                src={`data:image/jpeg;base64,${Buffer.from(userData.image).toString('base64')}`}
                alt="User Image"
              />
            </div>
          ))}
        </div>
      );
    }
    
    export default User;
    
    Login or Signup to reply.
  2. <img src={userData.image ? 'data:image;base64,' + userData.image : './Images/profile.png'} alt={userData.image ? 'User profile image' : 'Default image'} width="200" height="200" />
    

    It’s actually better to do it this way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search