上傳檔案到網站,Check 檔案大小,有下列幾種作法:
1.上傳檔案後由 Server 端程式進行確認,但這種方法不是很有效率
2.使用 Javascript 進行確認,但在測試過程中使用的 IE8.0 需要透過 ActiveX 元件取得檔案大
小,這種方法並不方便,至於 Firefox 可以使用 File API 中的 FileSize
(新版中改為HTML 5 標準屬性 size,FileSize 已經被 Deprecated )。
https://developer.mozilla.org/en/DOM/File
下列程式在 Firefox 3.6 與 Chrome 5.0 測試 OK,IE8 則不支持
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Check File Size</title>
</head>
<script type="text/javascript">
function check(){var size=document.getElementById("file1").files.item(0).size;if(size>10240000){alert("上傳檔案不得超過 10M ");return false;}
return true;}
</script>
<body>
<form action="#" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="file1" id="file1" />
<input type="submit" />
</form>
</body>
</html>
下列程式使用 ActiveX 元件方式,IE 8.0 測試 OK
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Check File Size</title>
</head>
<script type="text/javascript">
function check(){var obj = new ActiveXObject("Scripting.FileSystemObject");var size = obj.getFile(document.getElementById("file1").value).size;
if(size>10240000){alert("上傳檔案不得超過 10M ");return false;}
return true;}
</script>
<body>
<form action="#" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="file1" id="file1" />
<input type="submit" />
</form>
</body>
</html>
但使用時會跳出下列警告視窗,不是很方便
整理一下上述程式,使用到 IE 8.0 、Firefox 3.6、Chrome 5 瀏覽器
(使用測試瀏覽器 IE8、Firefox3.6、Chrome 5,請依需求更改下列程式)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Check File Size</title>
</head>
<script type="text/javascript">
function check(){var size=0;
if(navigator.userAgent.indexOf("MSIE")>-1){var obj = new ActiveXObject("Scripting.FileSystemObject");size = obj.getFile(document.getElementById("file1").value).size;}else if(navigator.userAgent.indexOf("Firefox")>-1|| navigator.userAgent.indexOf("Chrome")>-1){
size=document.getElementById("file1").files.item(0).size;
}else{return false;}
if(size>10240000){alert("上傳檔案不得超過 10M ");return false;}
return true;}
</script>
<body>
<form action="#" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="file1" id="file1" />
<input type="submit" />
</form>
</body>
</html>
3.使用 Flash Check 檔案大小,這種方式在 HTML 5 標準未被廣範支援前,是較好的解決方
案,可參考下列網站。
參考網站:
http://bytes.com/topic/javascript/answers/460516-check-file-size-javascript
全站熱搜
留言列表