I have images stored on S3 with description stored in metadata, following their recommendation for storing metadata
How can I retrieve the response headers when showing the image directly in the browser? I have tried looking in the onload event on an img element but can't find the headers. I have also tried XMLHttpRequest which gets me the headers in the response but I'm not then able to use the responseText as img src.
Eventually I found this fiddle and got the images via XMLHttpRequest, then set the desc from headers on to the image in a custom attribute:
function(image_path, img){
// Use a native XHR so we can use custom responseType
var xhr = new XMLHttpRequest();
xhr.open("GET", image_path, true);
// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
// Obtain a blob: URL for the image data to draw it
var arrayBufferView = new Uint8Array( this.response );
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
var imageUrl = URL.createObjectURL( blob );
img.src = imageUrl;
// Get the description from S3 metadata
var desc = this.getResponseHeader('x-amz-meta-description');
img.setAttribute('data-description', desc);
};
xhr.send();
}
If you need to get response headers before image loading or without image loading, you can use head query.When this query is executed, you will receive only headers, is much more efficient if you need only custom data without a file.
$.ajax({url:imageUrl,type:"HEAD"}).always(function(data,content,xhr){
var desc = xhr.getResponseHeader('x-amz-meta-description');
console.log(desc)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With