您的位置:首页 > Web前端 > JavaScript

js判断客户端文件大小

2009-10-11 09:45 344 查看
背景:上传文件前就先要在客户端判断文件大小,免得让用户传了很久后发现上传失败

在网上找了很久,东平西凑了下面的代码,测试在ff和ie中通过

不过对于ie,如果用户禁止了activex控件,则无法生效,但我没有找到更好的办法

网上还有用img来判断文件大小的,但我测试在ie7,8下不行,希望有高手能赐教

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>input type=file & Firefox 3</title>
</head>

<body>

<h1>input type=file & Firefox 3</h1>

<script type="text/javascript">
// <![CDATA[

function inputFileOnChange(files) {
if(document.getElementById('my-file').files) {

//for firefox
alert('fileSize: ' + document.getElementById('my-file').files.item(0).fileSize);

}
else{

//for IE

fso=new ActiveXObject("Scripting.FileSystemObject");
f=fso.GetFile(files);
// var mySize = f.size/1024;
// alert(mySize+" K ");
alert(f.size);

}

files="";
//alert(files);

};

// ]]>
</script>

<div>
<input type="file" name="my-file" id="my-file" onchange="inputFileOnChange(this.value);" />
</div>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: