1.jsp页面代码
<form id="userPhoto" name="userPhoto" method="post" action="../uploadUserPhoto" enctype="multipart/form-data">
<input type="hidden" id="max_PhotoSize" name="maxPhotoSize" value="${maxPhotoSize}"/>
<input type="hidden" id="photoType" name="photoType" value=""/>
<input type="file" id="filePhoto" value=""
style="font-size:400px;opacity:0;filter:alpha(opacity:0);-moz-opacity:0;position:absolute;top:0px;left:0px;width:400px;height:400px;z-index:100;overflow:hidden;cursor:pointer;"
name="userPhoto"/>
<img style="top:0px;left:0px;z-index:99" id="imgUserPhoto" src="" width="100" height="140">
<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0" align="center">
<tr>
<td width="100%" align="center" valign="middle">
<s:hidden id="userId" name="user.userId" />
</td>
</tr>
</table>
</form>
2. js代码
function uploadImage() {
var fileSize = 1024 * 5000;
var maxFileSize= $("#max_PhotoSize")[0].value ;
var location = $("#filePhoto")[0].value;
var point = location.lastIndexOf(".");
var type = location.substr(point);
$("#photoType").val(type);
if (type == ".jpg" || type == ".gif" || type == ".JPG" || type == ".GIF" || type == ".bmp" || type == ".BMP"
|| type == ".jpeg" || type == ".JPEG" || type == ".PNG" || type == ".png" ) {
if ($.browser.msie) {//IE
var img = document.createElement("img");
img.src = $("#filePhoto")[0].value;
fileSize = img.fileSize;
}
if ($.browser.mozilla || (navigator.userAgent.toLowerCase().match(/chrome/) !=null)) {//火狐或者chrome
fileSize = $("#filePhoto")[0].files[0].size;
}
if (fileSize > maxFileSize*1024) {
alert("图片尺寸请不要大于"+maxFileSize+"KB");
return false;
} else {
$("#userPhoto")[0].submit();
return true;
}
} else {
alert("只能上传jpg,gif,bmp,jpeg,png格式的图片");
return false;
}
return true;
}
3.补充:
以上关于IE的验证,适合于IE6以前的版本,对于IE7以上的版本前台不好判断图片的大小,最好还是通过后台判断:
(1)先将Form提交
(2)在后台判断提交图片文件大小,如果大于最大限制,则不做任何处理,返回提示语,如果在最大限制内,则再进行保存等处理