目录
- 基本思路
- 示例
[一]、基本思路
在FireFox、Chrome浏览器中可以根据document.getElementById(“id_file”).files[0].size 获取上传文件的大小(字节数),而IE浏览器中不支持该属性,只能借助<img>标签的dynsrc属性,来间接实现获取文件的大小(但需要同意ActiveX控件的运行)。
[二]、示例
测试代码:filesize-check.html
1 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
2 |
< html xmlns = "http://www.w3.org/1999/xhtml" > |
3 |
< head > |
4 |
< meta name = "DEscription" contect = "my code demo" /> |
5 |
< meta name = "Author" contect = "Michael@www.micmiu.com" /> |
6 |
< meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> |
7 |
< title >js check file size @ www.micmiu.com</ title > |
8 |
</ head > |
9 |
< body > |
10 |
< img id = "tempimg" dynsrc = "" src = "" style = "display:none" /> |
11 |
< input type = "file" name = "file" id = "fileuploade" size = "40" /> |
12 |
< input type = "button" name = "check" value = "checkfilesize" onclick = "checkfile()" /> |
13 |
14 |
</ body > |
15 |
< script type = "text/javascript" > |
16 |
var maxsize = 2*1024*1024;//2M |
17 |
var errMsg = "上传的附件文件不能超过2M!!!"; |
18 |
var tipMsg = "您的浏览器暂不支持计算上传文件的大小,确保上传文件不要超过2M,建议使用IE、FireFox、Chrome浏览器。"; |
19 |
var browserCfg = {}; |
20 |
var ua = window.navigator.userAgent; |
21 |
if (ua.indexOf("MSIE")>=1){ |
22 |
browserCfg.ie = true; |
23 |
}else if(ua.indexOf("Firefox")>=1){ |
24 |
browserCfg.firefox = true; |
25 |
}else if(ua.indexOf("Chrome")>=1){ |
26 |
browserCfg.chrome = true; |
27 |
} |
28 |
function checkfile(){ |
29 |
try{ |
30 |
var obj_file = document.getElementById("fileuploade"); |
31 |
if(obj_file.value==""){ |
32 |
alert("请先选择上传文件"); |
33 |
return; |
34 |
} |
35 |
var filesize = 0; |
36 |
if(browserCfg.firefox || browserCfg.chrome ){ |
37 |
filesize = obj_file.files[0].size; |
38 |
}else if(browserCfg.ie){ |
39 |
var obj_img = document.getElementById('tempimg'); |
40 |
obj_img.dynsrc=obj_file.value; |
41 |
filesize = obj_img.fileSize; |
42 |
}else{ |
43 |
alert(tipMsg); |
44 |
return; |
45 |
} |
46 |
if(filesize==-1){ |
47 |
alert(tipMsg); |
48 |
return; |
49 |
}else if(filesize>maxsize){ |
50 |
alert(errMsg); |
51 |
return; |
52 |
}else{ |
53 |
alert("文件大小符合要求"); |
54 |
return; |
55 |
} |
56 |
}catch(e){ |
57 |
alert(e); |
58 |
} |
59 |
} |
60 |
</ script > |
61 |
</ html > |
测试上传的文件大小:
各浏览器中的效果如下:
IE8:
FF(11.0):
Chrome(19.0.1084.56 m):
—————–