【问题标题】:Get response headers when loading an image from AWS S3从 AWS S3 加载图像时获取响应标头
【发布时间】:2014-08-21 15:51:12
【问题描述】:

我将图像存储在 S3 上,描述存储在元数据中,遵循 their recommendation for storing metadata

直接在浏览器中显示图像时如何检索响应标头?我尝试在 img 元素上查看 onload 事件,但找不到标题。我也尝试过 XMLHttpRequest,它可以让我获得响应中的标头,但我无法将 responseText 用作 img src。

【问题讨论】:

    标签: javascript html ajax amazon-s3 frontend


    【解决方案1】:

    最终我找到this fiddle 并通过 XMLHttpRequest 获取图像,然后在自定义属性中将标题中的 desc 设置为图像:

    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();
    }
    

    【讨论】:

      【解决方案2】:

      如果您需要在加载图像之前或不加载图像之前获取响应头,您可以使用头部查询。执行此查询时,您将只收到头,如果您只需要没有文件的自定义数据,则效率更高。

              $.ajax({url:imageUrl,type:"HEAD"}).always(function(data,content,xhr){
                   var desc = xhr.getResponseHeader('x-amz-meta-description');
                   console.log(desc)
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-11
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多