JavaScript - 从HTML img src获取字节大小 [英] JavaScript - Get size in bytes from HTML img src

查看:1096
本文介绍了JavaScript - 从HTML img src获取字节大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

我想知道如何从img标签的src中获取字节大小。 code>< img src =https://ofbuckleyandbeatles.files.wordpress.com/2011/01/testpattern.gif/>

在上面的例子中,我基本上想知道testpattern.gif有多大(以字节为单位)。



预先感谢。

解决方案

Javscript是一个纯粹的客户端脚本,如果你问我是否只能使用JavaScript获取图像大小,那么我的答案是NO。即使您在本地运行文件,也无法获得文件大小。



XMLHttpRequest对象 $ b

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

这主要用于发送 http https <强请求到场景后面的服务器,并将响应加载回脚本。这由现代浏览器支持,较旧的浏览器曾有类似的ActiveXObject。 onReadyStateChange 事件有5个准备阶段。


  • 0 =请求未初始化

  • 1 =建立服务器连接
  • 2 =接收到的请求

  • 3 =处理请求

  • 4 =处理完成并且响应已准备就绪



I would like to know how to get the size in bytes from the "src" from an "img" tag with HTML/JS.

<img src="https://ofbuckleyandbeatles.files.wordpress.com/2011/01/testpattern.gif"/>

In the above example I would basicly want to know how big "testpattern.gif" is (in bytes).

Thanks in advance.

解决方案

Javscript is a pure client side scripting and if you ask me whether we can get the image size only by using javascript, than my answer is "NO". Even if you run the files locally, you won’t be able to get the file size.

XMLHttpRequest object

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

This is basically used to send http or https request to a server behind the scene and load the response back to the script. This is supported by modern browsers, the older ones used to have a similar one called ActiveXObject. The onReadyStateChange event has its 5 ready stages.

  • 0=request not initialized
  • 1=server connection established
  • 2=request received
  • 3=processing request
  • 4=processing finished and response is ready

.

这篇关于JavaScript - 从HTML img src获取字节大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆