kylex
kylex

Reputation: 14406

Display image in html which is returned as a MIME media type from an ajax call

I'm trying to display an image in PNG format (it is returned as a MIME media type image/png from the following code). Does it need to be saved somehow?:

      $.ajax({
        type: "GET",
        url: url + "/api/image/",
        contentType: "image/png",
        async: false
      })
      .done(function(msg) {
        // msg IS THE MIME MEDIA TYPE PNG IMAGE
        // HOW DO I DISPLAY THIS IMAGE INSIDE AN HTML PAGE?
      })
      .fail(function(msg) {
        // failing is okay for image, just ignore it
      });

Upvotes: 1

Views: 1543

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

Here's a solution using pure Javascript (fiddle):

HTML

<div style="background-color: #4679bd; padding: .5em;">
    <img id="image"/>
</div>

Javascript

var request = new XMLHttpRequest();
request.open('GET','http://fiddle.jshell.net/img/logo.png', true);
request.responseType = 'arraybuffer';
request.onload = function(e) {
    var data = new Uint8Array(this.response);
    var raw = String.fromCharCode.apply(null, data);
    var base64 = btoa(raw);
    var src = "data:image/jpeg;base64," + base64;

    document.getElementById("image").src = src;
};

request.send();

It uses a Uint8Array and the responseType property of XMLHttpRequest Level 2, so your cross-browser mileage may vary. I've only tested in a recent version of Firefox and Chrome.

As far as a JQuery solution goes, I found a lot of discussion and some extensions, but nothing "official" so far.

Upvotes: 3

Related Questions