1. 程式人生 > 程式設計 >jquery檢測上傳檔案大小示例

jquery檢測上傳檔案大小示例

本文例項講述了jquery檢測上傳檔案大小。分享給大家供大家參考,具體如下:

google了很久,基本上都是用 activeX 來實現~至於為什麼不行,這個不多說,說一下以下方法:

已經測試通過的瀏覽器:IE6+,firefox,chrome,其中 firefox 和 chrome 要能支援 HTML5。

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=big5">
  <title>上傳</title>
</head>
<body>
  <form action="XXXXXX" method="POST" name="FileForm" enctype="multipart/form-data">
  <div align="center">
    圖片:
    <input type="file" name="file1" size="20" id="file1" />
    <input type="button" onclick="checkFile()" /></div>
  </form>
</body>
</html> 

<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>

<script language="JavaScript" type="text/javascript">
  var fileSize = 0; //檔案大小
  var SizeLimit = 1024; //上傳上限,單位:byte

  function checkFile() {
    var f = document.getElementById("file1");
    //FOR IE
    if ($.browser.msie) {
      var img = new Image();
      img.onload = checkSize;
      img.src = f.value;
    }
    //FOR Firefox,Chrome
    else {
      fileSize = f.files.item(0).size;
      checkSize();
    }
  }

  //檢查檔案大小
  function checkSize() {
    //FOR IE FIX
    if ($.browser.msie) {
      fileSize = this.fileSize;
    }

    if (fileSize > SizeLimit) {
      alert('檔案超過大小');
    } else {
      document.FileForm.submit();
    }
  }
</script>

更多關於jQuery相關內容感興趣的讀者可檢視本站專題:《jQuery頁面元素操作技巧彙總》、《jQuery常見事件用法與技巧總結》、《jQuery常用外掛及用法總結》、《jQuery擴充套件技巧總結》及《jquery選擇器用法總結》

希望本文所述對大家jQuery程式設計有所幫助。