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

用HTML的File控件上传图片,用JS判断和限制图片格式、类型、尺寸

2014-04-17 14:04 447 查看
//判断图片类型
var f=document.getElementById("File1").value;
if(f=="")
{ alert("请上传图片");return false;}
else
{
if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(f))
{
alert("图片类型必须是.gif,jpeg,jpg,png中的一种")
return false;
}
}


function CheckFile(f,p)
{
//判断图片尺寸
var img=null;
img=document.createElement("img");
document.body.insertAdjacentElement("beforeend",img);
img.style.visibility="hidden";
img.src=f;
var imgwidth=img.offsetWidth;
var imgheight=img.offsetHeight;
if(p.name=="UpFile_Photo1")
{
if(imgwidth!=68||imgheight!=68)
{
alert("小图的尺寸应该是68x68");
}
}
if(p.name=="UpFile_Photo2")
{
if(imgwidth!=257||imgheight!=351)
{
alert("中图的尺寸应该是257x351");
}
}
if(p.name=="UpFile_Photo3")
{
if(imgwidth!=800||imgheight!=800)
{
alert("大图的尺寸应该是800x800");
}
}
//判断图片类型
if(!/\.(gif|jpg|jpeg|bmp)$/.test(f))
{
alert("图片类型必须是.gif,jpeg,jpg,bmp中的一种")
return false;
}
return true;
}


<input type="file" id="UpFile_Photo1" runat="server" name="UpFile_Photo1"
size="35" onpropertychange="CheckFile(this.value,this)">小图<br />
<input type="file" id="UpFile_Photo2" runat="server" name="UpFile_Photo2"
size="35" onpropertychange="CheckFile(this.value,this)">中图<br />
<input type="file" id="UpFile_Photo3" runat="server" name="UpFile_Photo3"
size="35" onpropertychange="CheckFile(this.value,this)">大图<br />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: