方案1 :限定大小
<html>
<head>
<script type="text/javascript">
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(target) {
var fileSize = 0;
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024;
if(size>10000){
alert("附件不能大于10M");
}
}
</script>
</head>
<body>
<input type="file" name="contractFileName" style="width: 500px;" onchange="fileChange(this);"/>
</body>
</html>
方案2::限定大小
兼容ie6,ie7,ie8 ,Google Chrome,ff等浏览器,ie8上面在安全设置处设置一下就好了(工具 => Internet选项 => 安全 => Internet => 自定义级别 找到“将文件上载到服务器时包含本地目录路径”,设为“启用”即可)。
function fileChange(target) {
var fileSize = 0;
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
if(!fileSystem.FileExists(filePath)){
alert("附件不存在,请重新输入!");
var file=document.getElementById(id);
file.outerHTML=file.outerHTML;
return;
}
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024;
if(size>100000){
alert("附件大小不能大于100M!");
var file=document.getElementById(id);
file.outerHTML=file.outerHTML
}
if(size<=0){
alert("附件大小不能为0M!");
var file=document.getElementById(id);
file.outerHTML=file.outerHTML
}
}
限定上传类型
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<script type="text/javascript">
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(target) {
if(!(/(?:jpg|gif|png|jpeg)$/i.test(target.value))) {
alert(" 只允许上传jpg|gif|png|jpeg格式的图片");
if(window.ActiveXObject) {//for IE
target.select();//select the file ,and clear selection
document.selection.clear();
} else if(window.opera) {//for opera
target.type="text";target.type="file";
} else target.value="";//for FF,Chrome,Safari
return;
} else {
return; //alert("ok");//or you can do nothing here.
}
}
</script>
</head>
<body>
<input type="file" name="contractFileName" style="width: 500px;"
onchange="fileChange(this);" />
</body>
</html>