[javascript] How to display an image stored as byte array in HTML/JavaScript?

I'm writing a web page in HTML/JavaScript. I'm downloading an image from my backend using AJAX. The image is represented as raw byte array, not an URL, so I can't use the standard <img src="{url}"> approach.

How do I display the mentioned image to the user?

This question is related to javascript html

The answer is


Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions: