Get response headers when uploading an image from AWS S3

I have images stored on S3 with description stored in metadata following their recommendations for storing metadata

How can I get response headers when displaying an image directly in the browser? I tried to look in the onload event on the img element but can't find the headers. I've also tried XMLHttpRequest, which gets headers in the response, but I can't seem to use responseText as img src.

+3


source to share


2 answers


I eventually found this fiddle and got the images via XMLHttpRequest and then set desc from headers to the image in the 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();
}

      

+5


source


If you need to get response headers before loading images or without loading images, you can use chapter request. When this request is made, you will only get headers, much more efficient if you only want user 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)
        });

      

0


source







All Articles