Home > Enterprise >  how to show image from bytes?
how to show image from bytes?

Time:12-09

I have an API which returns an Image as byte data, but I don't know how can I show this bytes in the src of the img tag

here is an example of what I got in the result enter image description here

and this is how I use axios to make use of the API

const getFile = async (nombreArchivo) => { 
const tokenApp = window.localStorage.getItem('token')
const {data: res} = await axios.get(`${url}photo-2.jpg`,
{  headers: { Authorization: `${tokenApp}` },responseType: 'json',});
return res;};

CodePudding user response:

Add {responseType: 'blob'} to your axios config.

Then use <img src={URL.createObjectURL(responseData)} />to display it.

CodePudding user response:

You can convert the bytes array into the base64 encoding and use this for rendering the image.

byte[] to base64:

const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));

source of the conversion here

Once you have the base64 you can use it into the src field of a standard img tag

  • Related