Skip to content

Instantly share code, notes, and snippets.

@VANITAX
Created July 17, 2018 19:06
Show Gist options
  • Select an option

  • Save VANITAX/5b7b96b4e195519f4dd9a617f94145d0 to your computer and use it in GitHub Desktop.

Select an option

Save VANITAX/5b7b96b4e195519f4dd9a617f94145d0 to your computer and use it in GitHub Desktop.
jq 图片校验(图片格式,长度和宽度,容量大小)
<input type="file" id="photoInput" />
if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test($('#'+fileId).val())){
alert("上传图片格式错误,请重新上传");
return;
}
//验证是否支持HTML5
var fileUpload = document.getElementById("photoInput");
if (typeof(fileUpload.files) != "undefined") {
var reader = new FileReader();
//读取图片文件详细内容
reader.readAsDataURL($('#photoInput')[0].files[0]);
reader.onload = function(e) {
var image = new Image();
//从reader返回值,并且进行Base64的编码
image.src = e.target.result;
//验证文件的长度和高度
image.onload = function() {
var height = this.height;
var width = this.width;
if (height > 100 || width > 100) {
alert("Height and Width must not exceed 100px.");
return false;
} else {
alert("Uploaded image has valid Height and Width.");
return true;
}
}
} else {
alert("This browser does not support HTML5.");
return false;
}
}
$(document).ready(function() {
$("#photoInput").change(function() {
var iSize = ($("#photoInput")[0].files[0].size / 1024);
if (iSize / 1024 > 1) {
if (((iSize / 1024) / 1024) > 1) {
iSize = (Math.round(((iSize / 1024) / 1024) * 100) / 100);
$("#lblSize").html(iSize + "Gb");
} else {
iSize = (Math.round((iSize / 1024) * 100) / 100);
$("#lblSize").html(iSize + "Mb");
}
} else {
iSize = (Math.round(iSize * 100) / 100);
$("#lblSize").html(iSize + "kb");
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment