js上传文件长、宽、大小的限制

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="">
<input type="file" img-width='300,600' img-height='400,800' img-size='200' >
</form>
</body>
<script src="http://s.thsi.cn/js/ifund/mobile/zepto.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[type='file']").each(function(k,v){
var str = '';
if ($(v).attr('img-width') && $(v).attr('img-height')) {
var width = $(v).attr('img-width').split(',');
var height = $(v).attr('img-height').split(',');
if (width[0] && height[0]) {
str += "<span style='color:red;'>请上传" + width[0] + "px * " + height[0] + "px";
if (width[1] && height[1]) {
str += "或者 " + width[1] + "px * " + height[1] + "px";
}
str += "的图片";
}
}
if($(v).attr('img-size')){
str += ";不超过" + $(v).attr('img-size') + "K";
}
if (str) {
str += '</span>';
}
console.log(str);
$(v).after(str);
})
});
$("form").on("change", "input[type='file']",function(event){
//返回哪个 DOM 元素触发了事件
var t = $(event.target);
if (t.val()) {
var width = t.attr("img-width");
var height = t.attr("img-height");
var size = t.attr("img-size");
if (width && height) {
checkImgSize(t, width, height, 2);
}
if(size){
checkSize(t,size);
}
}
})
/**
* size 文件大小 K
*/
function checkSize(t,size){
var file = $(t)[0].files[0];
if (file.size/1024 > size ){
t.val("");
alert('图片大小不对');
}
}
/**
* width 宽度
* height 高度
* deviation 偏移度
*/
function checkImgSize(t, width, height, deviation){
var file = $(t)[0].files[0];
var image = new Image();
var flag = false;
width = width.split(',');
height = height.split(',');
image.onload = function () {
width[0] = parseInt(width[0]);
height[0] = parseInt(height[0]);
if (image.width >  width[0] + deviation || image.width < width[0] - deviation || image.height >  height[0] + deviation || image.height < height[0] - deviation) {
if (width[1] && height[1]) {
width[1] = parseInt(width[1]);
height[1] = parseInt(height[1]);
if (image.width >  width[1] + deviation || image.width < width[1] - deviation || image.height >  height[1] + deviation || image.height < height[1] - deviation) {
t.val("");
alert('图片尺寸不对');
}
} else {
t.val("");
alert('图片尺寸不对');
}
}
//console.log(image.width, image.height);
};
var fr = new FileReader();
fr.onload = function() {
image.src = fr.result;
};
fr.readAsDataURL(file);
}
</script>
</html>

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注