Michael 777
Michael 777

Reputation: 27

How to upload 1 image + convert to base64 + display the same image with the same ID multiple times on the same HTML page with javascript?

It works well but only display the image one time... Thank you for your help

<input type="file" id="file-upload" class="upload-file bg-highlight shadow-s rounded-s " accept="image/*">

<img id="image-data" src="images/empty.png" class="img-fluid">

<img id="image-data" src="images/empty.png" class="img-fluid">

<img id="image-data" src="images/empty.png" class="img-fluid">

<img id="image-data" src="images/empty.png" class="img-fluid">

Upvotes: 1

Views: 303

Answers (1)

ProDec
ProDec

Reputation: 5410

This could work as expected. Choose an image file and use FileReader to read image data.

document.getElementById('file-upload').addEventListener('change', e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
    document.querySelectorAll('#image-data').forEach(i => i.src = reader.result);
});
if (file) {
    reader.readAsDataURL(file);
}
});
#image-data { width: 100px; height: 100px; }
<input type="file" id="file-upload" class="upload-file bg-highlight shadow-s rounded-s " accept="image/*">

<img id="image-data" src="images/empty.png" class="img-fluid">

<img id="image-data" src="images/empty.png" class="img-fluid">

<img id="image-data" src="images/empty.png" class="img-fluid">

<img id="image-data" src="images/empty.png" class="img-fluid">

Upvotes: 1

Related Questions