Set Image Src from Amazon S3

I needed to request an image from Amazon S3 using ajax so I could read the response metadata headers. At first this seemed like a simple task. The first issue I encountered was that S3 was blocking the metadata headers from the browser using CORS. After a quick update to the S3 cors policy on the bucket, this issue was resolved. But what about turning the blob data type that comes from S3 into an img src. After several Google searches, I was finally able to get it to work. It was more difficult to find than I expected.

var loadImage = function (imageUrl) {
$.ajax({
type: 'GET',
url: imageUrl,
dataType: null,
data: null,
xhrFields: {
responseType: 'blob'
},
success: function (imageData) {
var blobUrl = window.URL.createObjectURL(imageData);
$('#image-id').attr('src', blobUrl);
}
});
};

Since Jquery ajax does not support the responseType: ‘blob’, you have to set the value in the xhrFields. The other important part is to use window.URL.createObjectURL to convert the blob to a url for the image src.

Hopefully this post helps!


Originally published at Tim Leland.