Search code examples
reactjsimageaxiosblob

Displaying an image in ReactJS from an API


I am getting an image from my API using the Axios library. I can see the image in Postman and in the Network tab on the browser, so I know the API is sending it and Axios gets it. But I dont know how to display it inside an <img>element.

This is what I've tried

const getPhoto = async ({jwtToken}) => {
    const apiEndpoint = 'http://localhost:8000/resources/photos/default.png'
    const config = {
        headers: {
            'Authorization' : `Bearer ${jwtToken}`,
            'responseType'  : 'arraybuffer'
        }
    }
    try {
        const response = await axios.get(apiEndpoint, config)
        const base64 = Buffer.from(response.data, 'binary').toString('base64')
        return `data:image/jpeg;base64,${base64}`
    } catch (error) { error => {console.log(error)} }
}

The returned value I then store inside a variable image setImage((await getPhoto({jwtToken}) )

and this is the <img> element <img src={image} />

But it doesnt display anything. What am I doing wrong?


Solution

  • if you are getting blob data data from the backend you can use the following:-

    try {
        const response = await axios.get(apiEndpoint, config);
        const blob = response.data; // Binary data
    
        // Convert the blob to base64
        const reader = new FileReader();
        reader.readAsDataURL(blob);
    
        return new Promise((resolve, reject) => {
            reader.onloadend = () => {
                const base64 = reader.result;
                resolve(base64);
            };
    
            reader.onerror = (error) => {
                reject(error);
            };
        });
    } catch (error) {
        console.log(error);
    }