首页 > 解决方案 > 使用 HTML5 文件 API 获取类中所有图像的大小

问题描述

我在一个页面上有几张图片,它们都有类

.imgToPrint

我想遍历列表并使用文件API 获取每个文件的大小。

我正在尝试这样

$(".imgToPrint").each(function(){               
 console.log( $(this).files[0].size );
});

但我收到错误Uncaught TypeError: Cannot read property '0' of undefined

如何获取此类中每个图像的文件大小?

标签: javascriptjqueryhtmlfile

解决方案


在这里找到了答案,我以这种方式实现了它

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

推荐阅读