上传时常常会碰到限制图片尺寸的需求,而在后台通过byte判断大小,虽可行,但如果在JS中判断显然是更好的选择,尤其是在不限制文件大小,只限制尺寸时。
通常会使用创建Image对象,或添加一个<img>来获取,
- 1.img标签方式
<input type="button" onclick="uploadFile()" value="验证" />
<img id="imgShow" src="img.png" /><pre name="code" class="javascript">
function uploadFile()
{
var imgWidth = document.getElementById("imgShow").width;
var imgHeight = document.getElementById("imgShow").height;
alert("宽度:"+imgWidth)
alert("高度:"+imgHeight)
}
效果图,测试结果:
由此可见,既然Img标签中的图片高宽均能获取,换句话说在文件上传时我们可以使用JS动态的创建一个Img对象,然后在获取高度宽度进行判断。
- 2. js 中的Image对象
图像对象:
建立图像对象:图像对象名称=new Image([宽度],[高度])
图像对象的属性: border complete height hspace lowsrc name src vspace width
图像对象的事件:onabort onerror onkeydown onkeypress onkeyup onload
var img = new Image;
img.src = "xxxx"; //浏览器中可以直接访问到的<span style="font-family: Arial, Helvetica, sans-serif;">图片</span><span style="font-family: Arial, Helvetica, sans-serif;">地址</span>
alert(img.height);
但,这样会发现它迟迟未达到我们想要的效果,发现在获取高度时总为0; 原因是,我们只创建了一个Image对象,并未将此对象load到浏览器中,也就是说此时浏览器是无法访问到该图片的,那么它自然无法获取成功。
var img=new Image();
img.onload=function(){alert(img.height);};
img.onerror=function(){alert("error!")};
img.src="xxxxxx";
function show(){alert("body is loaded");};
window.onload=show;
需要注意的是:src 属性一定要写到 onload 的后面,否则程序在 IE 中会出错。
运行上面的代码后,在不同的浏览器中进行测试,发现 IE 和 FF 是有区别的,在 FF 中,img 对象的加载包含在 body 的加载过程中,既是 img加载完之后,body 才算是加 载完毕,触发 window.onload 事件。在 IE 中,img 对象的加载是不包含在 body 的加载过程之中的,body 加载完毕,window.onload 事件触发时,img对象可能还未加 载结束,img.onload事件会在 window.onload 之后触发。 如若src中的URL路劲可以通过浏览器访问到,则程序会运行成功,可以获取到高度以及宽度
但是在上传文件时,我们普遍不能直接地得到当前上传文件的URL地址,所以当以上程序放在文件上传中时会发现,仍旧无法运行。
比如如下情况:
<pre name="code" class="javascript"><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script>
function setImg() {
var docObj = document.getElementById("imgPath");
var files = document.getElementById("imgPath").value;
if (null == files || '' == files) {
$.messager.alert('温馨提示','请上传图片封面信息。','info');
return;
}
if(!uploadType(finals(files,"suffix"))){
$.messager.alert('温馨提示','请上传bmp,png,gif,jpeg,jpg格式的图片','info');
return false;
};
if(!uploadfinaName(finals(files,"fileName"))){
$.messager.alert('温馨提示','上传失败,文件名称只能由“数字”、“字母”、或“_”组成','info');
return false;
};
if (docObj.files && docObj.files[0]) {
var img = new Image;
img.onload = function(){
alert(img.height);
var width = img.width;
var height=img.height;
var filesize = img
if(width!=480 || height!=1008){
alert("图片尺寸不符合,请重新上传....");
}else{
//后续操作 提交代码
}
};
img.onerror=function(){
alert("error!");
};
img.src=window.URL.createObjectURL(docObj.files[0]);
}
}
</script>
</head>
<body>
<input id="imgPath" type="file" onchange="setImg()"/>
</body>
</html>