Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get response headers when loading an image from AWS S3

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.

like image 833
apfrod Avatar asked Mar 19 '23 16:03

apfrod


2 Answers

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();
}
like image 134
apfrod Avatar answered Apr 01 '23 23:04

apfrod


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)
        });
like image 28
Alex Nikulin Avatar answered Apr 02 '23 00:04

Alex Nikulin