且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JS - File Reader API获取图像文件的大小和尺寸

更新时间:2023-02-23 19:30:34

这样的事情?

var oPreviewImg = new Image();
oPreviewImg.onload = function(){
  console.log(this.size);
  alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
  return true;
};

oPreviewImg.onerror = function(){
  alert("'" + this.name + "' failed to load.");
  return true;
}

oPreviewImg.src = "//placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";

var xhr = new XMLHttpRequest();
xhr.open('HEAD', oPreviewImg.src, true);
xhr.onreadystatechange = function() {
    console.log('this', this);
  if ( xhr.readyState == 4 ) {
    if ( xhr.status == 200 ) {
      alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
    } else {
      alert('ERROR');
    }
  }
};
xhr.send(null);

实时版本

更新实时版本替换为Fiddle,但是,到期跨站点脚本问题,不再有效地检索大小。

Update Live version replaced with Fiddle, however, due to cross site scripting concerns, the size is no longer being retrieved effectively.