Load image as BLOB using JQuery.

The other day, a restrictive web policy forced me to load external images as BLOB / media data. I then had to take that BLOB data and display it as an image. This is a short code snippet showing how I did this using the JQuery JavaScript library.

JQuery: responseType BLOB.

Take a look at the JavaScript code snippet below:

jQuery.ajax({
        url: 'http://example.com/image.jpg',
        xhrFields:{
            responseType: 'blob'
        },
        success: function(data){            
            var blobData = data;
            var url = window.URL || window.webkitURL;
            var src = url.createObjectURL(data);
            $('#result-image').attr("src", src);
        }
});

In the code above:

  • I set the image URL as http://example.com/image.jpg. You will obviously need to modify this URL to suit your own needs.
  • Using the xhrFields parameter, I told JQuery to expect a blob response type.
  • Once the blob data was successfully downloaded, I created a URL for the blob data using the URL.createObjectURL() method.
  • Finally, I appended this URL to the src attribute of an image with the ID “result-image”. Once again – you will probably need to modify that ID to suit your own needs if you intend on showing the blob data as an image.

Note that you may run into Access-Control-Allow-Origin issues if you do not have the relevant headers set on the external server that you are downloading the image from.

Hopefully, this guide will save somebody an hour or two!