HTML – Download image through AJAX and display it


AJAX was initially designed to be used with text data (JSON/HTML/XML) and that is why this requirement of downloading images using AJAX were never fulfilled.

But with HTML5, XHR2 has been introduced which allows us to get ArrayBuffer in ajax response and this is something which can be used to download image.

There are two approaches that could be taken.

  1. Download the image, create a blob object and use it as src in img.
  2. Download the image, and create data url and use it as src in img.


  
  
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
        var blob = new Blob([xhr.response], {
            type: xhr.getResponseHeader("Content-Type")
        });
        var imgUrl = window.URL.createObjectURL(blob);
        document.getElementById("img").src = imgUrl;
      }
    }
  xhr.responseType = "arraybuffer";
  xhr.open("GET","Hacker.jpg",true);
  xhr.send();
  




  
  
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
        document.getElementById("img").src = "data:"+xhr.getResponseHeader("Content-Type")+";base64," + btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response)));
      }
    }
  xhr.responseType = "arraybuffer";
  xhr.open("GET","Hacker.jpg",true);
  xhr.send();
  


Know more about XHR2 look at http://www.html5rocks.com/en/tutorials/file/xhr2/

One comment

  1. xhr.open(“GET”,”Hacker.jpg”,truexhr.send();

    xhr.send();

    probably needs to be:
    xhr.open(“GET”,”Hacker.jpg”,true);

    xhr.send();

    Thank you, for the helpfull specification

Leave a comment