JS收集:图片上传_限制格式、类型、尺寸
用HTML的File控件上传图片,用JS判断和限制图片格式、类型、尺寸
1
function CheckFile(f,p)
2
{
3
//判断图片尺寸
4
var img=null;
5
img=document.createElement("img");
6
document.body.insertAdjacentElement("beforeend",img);
7
img.style.visibility="hidden";
8
img.src=f;
9
var imgwidth=img.offsetWidth;
10
var imgheight=img.offsetHeight;
11
if(p.name=="UpFile_Photo1")
12
{
13
if(imgwidth!=68||imgheight!=68)
14
{
15
alert("小图的尺寸应该是68x68");
16
}
17
}
18
if(p.name=="UpFile_Photo2")
19
{
20
if(imgwidth!=257||imgheight!=351)
21
{
22
alert("中图的尺寸应该是257x351");
23
}
24
}
25
if(p.name=="UpFile_Photo3")
26
{
27
if(imgwidth!=800||imgheight!=800)
28
{
29
alert("大图的尺寸应该是800x800");
30
}
31
}
32
//判断图片类型
33
if(!/\.(gif|jpg|jpeg|bmp)$/.test(f))
34
{
35
alert("图片类型必须是.gif,jpeg,jpg,bmp中的一种")
36
return false;
37
}
38
return true;
39
}
相关的HTML代码
function CheckFile(f,p)2
{3
//判断图片尺寸4
var img=null;5
img=document.createElement("img");6
document.body.insertAdjacentElement("beforeend",img);7
img.style.visibility="hidden"; 8
img.src=f;9
var imgwidth=img.offsetWidth;10
var imgheight=img.offsetHeight;11
if(p.name=="UpFile_Photo1")12
{13
if(imgwidth!=68||imgheight!=68)14
{15
alert("小图的尺寸应该是68x68");16
}17
}18
if(p.name=="UpFile_Photo2")19
{20
if(imgwidth!=257||imgheight!=351)21
{22
alert("中图的尺寸应该是257x351");23
}24
}25
if(p.name=="UpFile_Photo3")26
{27
if(imgwidth!=800||imgheight!=800)28
{29
alert("大图的尺寸应该是800x800");30
}31
}32
//判断图片类型33
if(!/\.(gif|jpg|jpeg|bmp)$/.test(f))34
{35
alert("图片类型必须是.gif,jpeg,jpg,bmp中的一种")36
return false;37
}38
return true;39
}1
<input type="file" id="UpFile_Photo1" runat="server" name="UpFile_Photo1"
2
size="35" onpropertychange="CheckFile(this.value,this)">小图<br />
3
<input type="file" id="UpFile_Photo2" runat="server" name="UpFile_Photo2"
4
size="35" onpropertychange="CheckFile(this.value,this)">中图<br />
5
<input type="file" id="UpFile_Photo3" runat="server" name="UpFile_Photo3"
6
size="35" onpropertychange="CheckFile(this.value,this)">大图<br />
<input type="file" id="UpFile_Photo1" runat="server" name="UpFile_Photo1" 2
size="35" onpropertychange="CheckFile(this.value,this)">小图<br />3
<input type="file" id="UpFile_Photo2" runat="server" name="UpFile_Photo2" 4
size="35" onpropertychange="CheckFile(this.value,this)">中图<br />5
<input type="file" id="UpFile_Photo3" runat="server" name="UpFile_Photo3" 6
size="35" onpropertychange="CheckFile(this.value,this)">大图<br />




浙公网安备 33010602011771号