Skip to content
Advertisement

Server send an raw image in axios, how to convert it to base64 or other way to use this image

From the following link, I get an image. Unfortunately, it shows the image in the preview tab of inspect element of the network. but in res.data it shows broken text. How will I be able to use this image in img tag like . I also shared what it returns to me in console and preview

export const getProfilePhoto = async (userType) => {
    return await axios.get(`${API_URL}/staff/profile-photo`,{ headers : authHeader(userType) })
    .then((res) => {
        console.log(res.data)
    })
}

This is what it shows in console

enter image description here

this is what it shows in preview

enter image description here

highly expecting some suggestions and solution

I’m sorry for any mistakes.

Advertisement

Answer

Ideally, you find a way to access this image without needing the extra headers, so you can just let the browser handle it directly:

<img src="{API_URL}/staff/profile-photo" />

If you can’t do that, then you will need to get a blob and create an object URL.

fetch(
  `${API_URL}/staff/profile-photo`,
  {
    headers: authHeader(userType)
  }
).then(res => res.blob()).then((blob) => {
  img.src = URL.createObjectURL(blob);
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement