Search code examples
javascriptxmlhttprequest

How to GET a .jpg image using XMLHttpRequest?


I can easily grab a .txt file for example using this method but when I try to get an image it sends a bunch of unencoded letters like these �@R�J�, how can I get the image as it is?

<!DOCTYPE html>
<html>
<body>

<h1 id="demo">Let AJAX change this text</h1>

<button id="button">Change Content</button>

<script>
document.getElementById('button').addEventListener('click', function(){

  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "images.jpg", true);
  xhttp.send();

});
</script>

</body>
</html>

Edit:

I have actually figured out I can do this document.getElementById("demo").setAttribute('src', 'https://placeimg.com/640/480/any');

and in the HTML <img id="demo" src="" />

And it works fine for an external resource but what about an image that's living in my server?


Solution

  • If the image is on your server you can get it by absolute address src="http://localhost:portnumber/pathOfTheImage/image.png" or relatively to your site folder, src="/images/image.png".