【问题标题】:Get response headers when loading an image from AWS S3从 AWS S3 加载图像时获取响应标头
【发布时间】:2014-08-21 15:51:12
【问题描述】:
【问题讨论】:
标签:
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)
});