Display a blob image

I work on a react project and I have login and register operations. In the register page I have a form which contains several inputs: name, email, profile image url, password and repeat password.

Now, the profile image url input is not required and that is why I want the app to randomly pick and display an image from an array of image urls.

Each image is uploaded in a folder in google drive. Then I convert each image to a blob image, however I can see the blob image in the browser but it doesn’t display to the user.

Here are some code snippets:

import fetch from "node-fetch";
import profileimages from "../profileImages.js";

export const images = async (req, res) => {
  try {
    // Randomly select an image URL
    const randomIndex = Math.floor(Math.random() * profileimages.length);
    const randomImageUrl = profileimages[randomIndex];

    // Fetch the random image
    const response = await fetch(randomImageUrl);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // Ensure the Content-Type header is set correctly
    const contentType = response.headers.get('content-type');
    if (!contentType) {
      throw new Error('Content-Type header is missing in the response');
    }

    // Fetch the image as an ArrayBuffer
    const arrayBuffer = await response.arrayBuffer();

    // Create a Buffer from the ArrayBuffer
    const imageBuffer = Buffer.from(arrayBuffer);

    // Set the Content-Type header in the response
    res.setHeader('Content-Type', contentType);
    // Send the image buffer in the response
    res.send(imageBuffer);
  } catch (error) {
    console.error('Error fetching image:', error);
    res.status(500).send('Internal Server Error');
  }
};
export const getUserProfileImage = async () => {
    try {
      const response = await fetch('http://localhost:5500/images/user');
  
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
  
      const blob = await response.blob();
      
      const imageUrl = URL.createObjectURL(blob);
  
      return imageUrl;
    } catch (err) {
      console.error('Error getting user profile image:', err);
      throw err;
    }
  };

export const register = async(data) =>{
    const body = {
        name: data.name,
        email: data.email,
        userImage: data.userImage || await getUserProfileImage(),
        password: data.password,
        rPassword: data.rPassword,
    }

    if(body.password !== body.rPassword){
        alert("Passwords need to match!");
        throw new Error("Passwords need to match!");
    }
    console.log(body)

    let response = await fetch(baseUrlRegister, {
        method: "POST",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(body),
    })
    const result = await response.json();
    console.log(result)

    if(result.status != 200){
            alert(result.message)
            throw new Error(result.message);
    }

    localStorage.setItem("accessToken", result.accessToken);
    localStorage.setItem("auth", [result.data.name, result.data.email, result.data._id])
    

    return result;
}

export function RegisterPage(){
  //const accessToken = localStorage.getItem("accessToken")

  const [imageUrl, setImageUrl] = useState('');

useEffect(() => {
  const loadImage = async () => {
    try {
      const blob = await userService.getUserProfileImage();
      setImageUrl(blob);
    } catch (error) {
      console.error('Error loading image:', error);
    }
  };

  loadImage();
}, []);

  let navigate = useNavigate()
  async function register(e){
    e.preventDefault();

    //

    if(document.getElementById("userImage").value == ""){
      document.getElementById("userImage").value = imageUrl;
    }

    // Get data from form data
    const data = Object.fromEntries(new FormData(e.target.form));
    console.log(data)

    // Create new user at the server
    await userService.register(data);
    document.getElementById("fullName").value = "";
    document.getElementById("email").value = "";
    document.getElementById("userImage").value = "";
    document.getElementById("pass").value = "";
    document.getElementById("rPass").value = "";

    navigate("/")
  }
 useEffect(() => {
      userService.getOne(userId)
        .then(result => setUserImage(result.userImage))
    })
<p>
            {''}
            Profile Image: {<img src={userImage} alt="profileImage"></img>}{' '}
          </p>

profile image display

register page

I tried using base64 but it didn’t work either

  • 2

    This comment is not related to the question, but why wouldn’t you host these images in a public folder in your node.js server and send frontend the URL of those images? It’d be the easiest way to implement your requirement in this scenario. Please correct me if I’m mssing anything.

    – 

  • 1

    @Pavindu It worked! Thanks! All this time I have been making it more and more complicated and now I got rid of almost everything I have given you above.

    – 

Leave a Comment