關於javascript判斷檔案大小-

來源:互聯網
上載者:User

   對於web開發人員來說檔案上傳檔案是經常遇到的,判斷檔案大小也是不可缺少,在這裡主要介紹一下javascript判斷檔案大小的幾種常見的方法。

   第一種是應用ActiveX控制項的實現,例如:
Javascript代碼

  1. <script type="text/javascript">  
  2. function getFileSize(filePath)  
  3. {  
  4.    var fso = new ActiveXObject("Scripting.FileSystemObject");  
  5.    alert("檔案大小為:"+fso.GetFile(filePath).size);  
  6. }  
  7. </script>  
  8. <body>  
  9. <INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value);">  
  10. </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... , 代碼如下:

Javascript代碼
  1. <script type="text/javascript">  
  2. function getFileSize(filePath)  
  3. {  
  4.    var image=new Image();  
  5.    image.dynsrc=filePath;  
  6.    alert(image.fileSize);  
  7. }  
  8. </script>  
  9. <body>  
  10. <INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value)">  
  11. </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>

經測試,得到檔案大小,並未出現安全提示,推薦,沒的說

轉自:http://kokobox.javaeye.com/blog/227071

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.