Mysterious Mysterious - 1 month ago 10
HTML Question

Dynamic uploaded image not shown in html

I have an application where I upload images dynamically and show them in the same page via the given script.

JS

document.getElementById("picture").innerHTML = "<img src='absolute_server_url'/>";


HTML

<div id="picture">
</div>


The problem is my image uploads successfully but the updated image is not shown in the html page.


Image name also remains same. I mean when I upload a new image I name that image same as the previous one. May be this will create a problem.


.

Answer

As you're uploading the image to the same filename this image will be potentially cached on the client.

You can get around this by cache-busting.

The simplest method in your example is to attach the current date/time as a query string.

Furthermore rather than use innerHtml it would be better to build your img element and set the src.

var img = document.createElement("img");
img.src = "absolute_server_url?dt=" + Date.now();
document.getElementById("picture").appendChild(img);