js判断文件大小

第一种是应用ActiveX控件的实现,例如

 <script type="text/javascript">      
function getFileSize(filePath)      
{      
   var fso = new ActiveXObject("Scripting.FileSystemObject");      
   alert("文件大小为:"+fso.GetFile(filePath).size);      
}      
</script>      
<body>      
<INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value);">      
</body>    
<script type="text/javascript"> 
function getFileSize(filePath)  
{  
   var fso = new ActiveXObject("Scripting.FileSystemObject");  
   alert("文件大小为:"+fso.GetFile(filePath).size);  
}  
</script> 
<body> 
<INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value);"> 
</body>  

这种方法可以实现,也容易被开发人员想到,但是唯一不足之处是有安全提示,当然把文件名改为.hta则会屏蔽掉安全提示,但很难被需求所取。不推荐,也不多下面主要谈谈另一种方式,在html标签中有一个不为一般开发人员“深”知的img标签,先来说下他有的属性:src,dynsrc,start,alt,controls,loop,loopdelay,hspace,vspace....还有一些常用的属性就不列出来了,在这里我们说一下"dynsrc"这个属性:dynsrc可以用来插入各种多媒体,格式可以是Wav、Avi、AIFF、AU、MP3、Ra、Ram等等。url为音频或视频文件及其路径,可以是相对路径或绝对路径。

示例:<img dynsrc="xxxx.mp3">

这样我们就可以根据dynsrc动态赋值任何类型文件的路径,在javascript中根据Image对象本身的fileSize属性来得到文件的大小。当然Image对象还有其他的几个属性,例如:fileCreatedDate、fileModifiedDate、fileSize、fileUpdatedDate、filters... , 代码如下:
<script type="text/javascript">      
function getFileSize(filePath)      
{      
   var image=new Image();      
   image.dynsrc=filePath;      
   alert(image.fileSize);      
}      
</script>      
<body>      
<INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value)">      
</body>    
<script type="text/javascript"> 
function getFileSize(filePath)  
{  
   var image=new Image();  
   image.dynsrc=filePath;  
   alert(image.fileSize);  
}  
</script> 
<body> 
<INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value)"> 
</body>  

再来个完整些的

<script language="javascript">
   var oForm = new Object();
   var oImage = new Image();
   oImage.attachEvent('onload',getSize);
   oImage.attachEvent('onerror',doWithError);
   function checkImage(obj){
      oForm = obj;
      oImage.src = oForm.oFile.value;           
   }
   function getSize(){
      var oImgSize = Math.floor(oImage.fileSize/1024);
      document.body.appendChild(oImage);
      if(oImgSize<200){
         if(window.confirm('您确定上传此图片吗?')){
            oForm.submit();
         }else{
            oForm.reset();
            return;
         }
      }else{
         window.alert('不允许上传大于200KB的图片!');
         oForm.reset();
      }
      var oIEVersion = window.navigator.appVersion;
      if(oIEVersion.indexOf('MSIE 6.0')!=-1){ oImage.removeNode(true); }
   }
   function doWithError(){
      window.alert('出现错误,请重新选择图片!');
      oForm.reset();
   }
</script>
<form method="post" enctype="multipart/form-data">
   <input type="file" name="oFile" onkeydown="return false;" oncontextmenu="return false;" onpaste="return false;" ondragenter="return false;" onpropertychange="checkImage(form);">
</form>

原文地址:https://www.cnblogs.com/cuihongyu3503319/p/1524505.html