2014-10-17 144 views
3

我在下面的代码中尝试从实际URL获取图片大小(以KB/MB/GB为单位)。但它不起作用。如何从网址获取图片大小

var xhr = new XMLHttpRequest(); 

xhr.open('HEAD', 'http://www.2015autoblog.com/wp-content/uploads/2014/09/2015-Toyota-Land-Cruiser-Front.jpg', true); 

调试

alert(xhr.status); 

if (xhr.status == 200) { 
    alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length')); 
} else { 
    alert('ERROR'); 
} 

回答

11

试试这个代码,它正在

var tmpImg = new Image(); 
tmpImg.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png"; //or document.images[i].src; 
$(tmpImg).one('load',function(){ 
    orgWidth = tmpImg.width; 
    orgHeight = tmpImg.height; 
    alert(orgWidth+"x"+orgHeight); 
}); 

上面的代码将获取图像尺寸。

对于文件大小: 不,您无法使用jQuery或纯JavaScript获取图像大小。唯一的方法是使用ajax从服务器端获取它。

您可以将图像的URL发送到服务或服务器端页面,并让页面或服务返回图像大小。

+2

不是高度和宽度。我需要KB/MB的大小。如1 MB等 – 2014-10-17 08:00:48

+0

您是否找到任何解决方案? – 2017-09-07 13:17:54