项目中用了Apache FileUpload上传组件进行图片上传,对于上传文件的大小的判断一直未找到好的解决方法,今天无意在网上看到用JAVASCRIPT在客户端实现了文件的大小判断的脚本,共享一下。
<form name="form" action="${pageContext.request.contextPath}/common/fileUpload.do?method=uploadImage" method="post" οnsubmit="return check();" enctype="multipart/form-data">
<table width="750" border="0" cellpadding="0" cellspacing="1" bgcolor="#82A9F5">
<tr>
<td align="left" colspan="2" height="25" bgcolor="#FFFFFF"><strong>上传新图片到图片库</strong></td>
</tr>
<tr bgcolor="#DEECFF">
<td height="25" align="left">请选择图片类型:</td>
<td height="25" align="left">
<input id="radio1" name="imagetype" type="radio" value="0" checked />产品图片
<input id="radio2" name="imagetype" type="radio" value="1" />广告图片
</td>
</tr>
<tr bgcolor="#FFFFFF">
<td height="25" align="left">请选择图片:</td>
<td height="25" align="left">
<input type="file" id="photo" name="photo" size="50"
<%-- 看清楚了,判断文件的大小的脚本就在这里啦! --%>
onpropertychange="if(document.form.photo.value!=''){document.getElementById('PhotoImg').src=document.form.photo.value;}"/>
<IMG style="POSITION:absolute; TOP:-100000px;left:-100000px;" οnerrοr="document.all.PhotoFileSize.value='-1';alert('请选择一个图像文件');"
οnlοad="if(document.getElementById('PhotoImg').fileSize<=1024*FileMaxSize){preview();
document.all.PhotoFileSize.value=document.getElementById('PhotoImg').fileSize;
document.all.upload.disabled=false}else{alert('图片不能大于'+FileMaxSize+'K,请重新选择');
document.all.PhotoFileSize.value='-1';document.all.upload.disabled=true}"
id="PhotoImg"> <input size="3" type="hidden" name="PhotoFileSize" value="-1" />
<% -- 结束 --%>
</td>
</tr>
<tr>
<td colspan="2" height="25" bgcolor="#FFFFFF"><input type="submit" name="upload" value="上 传" ></td>
</tr>
<tr>
<td align="left" colspan="2" height="25" bgcolor="#DEECFF">说明:上传图片的格式为JPG/JPEG/GIF,大小为300kb以下</td>
</tr>
</table>
</form>
<script type="text/javascript">
var FileMaxSize = 300;//限制上传的文件大小,单位(k)
function preview(){
var x = document.getElementById("photo");
if(!x || !x.value) return;
var patn = //.jpg$|/.jpeg$|/.gif$/i;
if(patn.test(x.value)){
var y = document.getElementById("img");
if(y){
y.src = 'file://localhost/' + x.value;
}else{
var img=document.createElement('img');
img.setAttribute('src','file://localhost/'+x.value);
img.setAttribute('width','220');
img.setAttribute('height','150');
img.setAttribute('id','img');
document.getElementById('form').appendChild(img);
}
}else{
alert("你选择的不是图片文件!");
}
}
function check(){
var x = document.getElementById("photo");
if(!x || !x.value){
alert("请选择一个图片文件");
return false;
}
return true;
} </script>