最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get response headers when loading an image from AWS S3 - Stack Overflow

programmeradmin3浏览0评论

I have images stored on S3 with description stored in metadata, following their remendation 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.

I have images stored on S3 with description stored in metadata, following their remendation 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.

Share Improve this question asked Aug 21, 2014 at 15:51 apfrodapfrod 3413 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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)
        });
发布评论

评论列表(0)

  1. 暂无评论